path
stringlengths
5
300
repo_name
stringlengths
6
76
content
stringlengths
26
1.05M
ajax/libs/yui/3.4.0pr2/yui/yui.js
blairvanderhoof/cdnjs
/** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and * the core utilities for the library. * @module yui * @submodule yui-base */ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** * The YUI global namespace object. If YUI is already defined, the * existing YUI object will not be overwritten so that defined * namespaces are preserved. It is the constructor for the object * the end user interacts with. As indicated below, each instance * has full custom event support, but only if the event system * is available. This is a self-instantiable factory function. You * can invoke it directly like this: * * YUI().use('*', function(Y) { * // ready * }); * * But it also works like this: * * var Y = YUI(); * * @class YUI * @constructor * @global * @uses EventTarget * @param o* {object} 0..n optional configuration objects. these values * are store in Y.config. See config for the list of supported * properties. */ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); // YUI.GlobalConfig is a master configuration that might span // multiple contexts in a non-browser environment. It is applied // first to all instances in all contexts. if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } // YUI_Config is a page-level config. It is applied to all // instances created on the page. This is applied after // YUI.GlobalConfig, and before the instance level configuration // objects. if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a ' // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', DOC_LABEL = 'yui3-js-enabled', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.3.0'; // dev time hack for cdn test } proto = { /** * Applies a new configuration object to the YUI instance config. * This will merge new group/module definitions, and will also * update the loader cache if necessary. Updating Y.config directly * will not update the cache. * @method applyConfig * @param {object} the configuration object. * @since 3.2.0 */ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, rls = config.rls, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (rls && name == 'rls') { clobber(rls, attr); } else if (name == 'win') { config[name] = attr.contentWindow || attr; config.doc = config[name].document; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, _config: function(o) { this.applyConfig(o); }, /** * Initialize this YUI instance * @private */ _init: function() { var filter, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** * The version number of the YUI instance. * @property version * @type string */ Y.version = VERSION; if (!Env) { Y.Env = { mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-rls" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-rls/yui-rls.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path } } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/\./g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { win: win, doc: doc, debug: true, useBrowserConsole: true, throwFail: true, bootstrap: true, cacheUse: true, fetchCSS: true, use_rls: false }; Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || ['get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3']; for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); }, /** * Executes a method on a YUI instance with * the specified id if the specified method is whitelisted. * @method applyTo * @param id {string} the YUI instance id. * @param method {string} the name of the method to exectute. * Ex: 'Object.keys'. * @param args {Array} the arguments to apply to the method. * @return {object} the return value from the applied method or null. */ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m.apply(instance, args); } return null; }, /** * Registers a module with the YUI global. The easiest way to create a * first-class YUI module is to use the YUI component build tool. * * http://yuilibrary.com/projects/builder * * The build system will produce the YUI.add wrapper for you module, along * with any configuration info required for the module. * @method add * @param name {string} module name. * @param fn {Function} entry point into the module that * is used to bind module to the YUI instance. * @param version {string} version string. * @param details {object} optional config data: * requires: features that must be present before this module can be * attached. * optional: optional features that should be present if loadOptional * is defined. Note: modules are not often loaded this way in YUI 3, * but this field is still useful to inform the user that certain * features in the component will require additional dependencies. * use: features that are included within this module which need to * be attached automatically when this module is attached. This * supports the YUI 3 rollup system -- a module with submodules * defined will need to have the submodules listed in the 'use' * config. The YUI component build tool does this for you. * @return {YUI} the YUI instance. * */ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, loader, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { loader = instances[i].Env._loader; if (loader) { if (!loader.moduleInfo[name]) { loader.addModule(details, name); } } } } return this; }, /** * Executes the function associated with each required * module, binding the module to the YUI instance. * @method _attach * @private */ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, done = Y.Env._attached, len = r.length, loader; //console.info('attaching: ' + r, 'info', 'yui'); for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name]) { Y._attach(aliases[name]); continue; } if (!mod) { loader = Y.Env._loader; if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; if (mod.use) { moot = true; } } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot) { if (name.indexOf('skin-') === -1) { Y.Env._missed.push(name); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } details = mod.details; req = details.requires; use = details.use; after = details.after; if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** * Attaches one or more modules to the YUI instance. When this * is executed, the requirements are analyzed, and one of * several things can happen: * * - All requirements are available on the page -- The modules * are attached to the instance. If supplied, the use callback * is executed synchronously. * * - Modules are missing, the Get utility is not available OR * the 'bootstrap' config is false -- A warning is issued about * the missing modules and all available modules are attached. * * - Modules are missing, the Loader is not available but the Get * utility is and boostrap is not false -- The loader is bootstrapped * before doing the following.... * * - Modules are missing and the Loader is available -- The loader * expands the dependency tree and fetches missing modules. When * the loader is finshed the callback supplied to use is executed * asynchronously. * * @param modules* {string} 1-n modules to bind (uses arguments array). * @param *callback {function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. * <code> * // loads and attaches dd and its dependencies * YUI().use('dd', function(Y) &#123;&#125); * // loads and attaches dd and node as well as all of their dependencies * YUI().use(['dd', 'node'], function(Y) &#123;&#125); * // attaches all modules that are available on the page * YUI().use('*', function(Y) &#123;&#125); * // intrinsic YUI gallery support (since 3.1.0) * YUI().use('gallery-yql', function(Y) &#123;&#125); * // intrinsic YUI 2in3 support (since 3.1.0) * YUI().use('yui2-datatable', function(Y) &#123;&#125);. * </code> * * @return {YUI} the YUI instance. */ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } }, _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, handleRLS, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { if (!names.length) { return; } YArray.each(names, function(name) { // add this module to full list of things to attach if (!skip) { r.push(name); } // only attach a module once if (used[name]) { return; } var m = mods[name], req, use; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } }); }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if (missing.sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = false; Y._use(args, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { ret = Y._attach(Y.Object.keys(mods)); if (ret) { handleLoader(); } return Y; } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; } // process each requirement and any additional requirements // the module metadata specifies process(args); len = missing.length; if (len) { missing = Y.Object.keys(YArray.hash(missing)); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(args); loader.insert(null, (fetchCSS) ? null : 'js'); // loader.partial(missing, (fetchCSS) ? null : 'js'); } else if (len && Y.config.use_rls) { G_ENV._rls_queue = G_ENV._rls_queue || new Y.Queue(); // server side loader service handleRLS = function(instance, argz) { var rls_end = function(o) { handleLoader(o); G_ENV._rls_in_progress = false; if (G_ENV._rls_queue.size()) { G_ENV._rls_queue.next()(); } }, rls_url = instance._rls(argz); if (rls_url) { instance.rls_oncomplete(function(o) { rls_end(o); }); instance.Get.script(rls_url, { data: argz }); } else { rls_end({ data: argz }); } }; G_ENV._rls_queue.add(function() { G_ENV._rls_in_progress = true; Y.rls_locals(Y, args, handleRLS); }); if (!G_ENV._rls_in_progress && G_ENV._rls_queue.size()) { G_ENV._rls_queue.next()(); } } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** * Returns the namespace specified and creates it if it doesn't exist * <pre> * YUI.namespace("property.package"); * YUI.namespace("YAHOO.property.package"); * </pre> * Either of the above would create YUI.property, then * YUI.property.package (YAHOO is scrubbed out, this is * to remain compatible with YUI2) * * Be careful when naming packages. Reserved words may work in some browsers * and not others. For instance, the following will fail in Safari: * <pre> * YUI.namespace("really.long.nested.namespace"); * </pre> * This fails because "long" is a future reserved word in ECMAScript * * @method namespace * @param {string*} arguments 1-n namespaces to create. * @return {object} A reference to the last namespace object created. */ namespace: function() { var a = arguments, o = this, i = 0, j, d, arg; for (; i < a.length; i++) { // d = ('' + a[i]).split('.'); arg = a[i]; if (arg.indexOf(PERIOD)) { d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: NOOP, /** * Report an error. The reporting mechanism is controled by * the 'throwFail' configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown * @method error * @param msg {string} the error message. * @param e {Error|string} Optional JS error that was caught, or an error string. * @param data Optional additional info * and throwFail is specified, this error will be re-thrown. * @return {YUI} this YUI instance. */ error: function(msg, e, data) { var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (Y.config.throwFail && !ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error'); // don't scrub this one } return Y; }, /** * Generate an id that is unique among all YUI instances * @method guid * @param pre {string} optional guid prefix. * @return {string} the guid. */ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** * Returns a guid associated with an object. If the object * does not have one, a new one is created unless readOnly * is specified. * @method stamp * @param o The object to stamp. * @param readOnly {boolean} if true, a valid guid will only * be returned if the object has one assigned to it. * @return {string} The object's guid or null. */ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** * Destroys the YUI instance * @method destroy * @since 3.3.0 */ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** * instanceof check for objects that works around * memory leak in IE when the item tested is * window/document * @method instanceOf * @since 3.3.0 */ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; } }()); /** * The config object contains all of the configuration options for * the YUI instance. This object is supplied by the implementer * when instantiating a YUI instance. Some properties have default * values if they are not supplied by the implementer. This should * not be updated directly because some values are cached. Use * applyConfig() to update the config object on a YUI instance that * has already been configured. * * @class config * @static */ /** * Allows the YUI seed file to fetch the loader component and library * metadata to dynamically load additional dependencies. * * @property bootstrap * @type boolean * @default true */ /** * Log to the browser console if debug is on and the browser has a * supported console. * * @property useBrowserConsole * @type boolean * @default true */ /** * A hash of log sources that should be logged. If specified, only * log messages from these sources will be logged. * * @property logInclude * @type object */ /** * A hash of log sources that should be not be logged. If specified, * all sources are logged if not on this list. * * @property logExclude * @type object */ /** * Set to true if the yui seed file was dynamically loaded in * order to bootstrap components relying on the window load event * and the 'domready' custom event. * * @property injected * @type boolean * @default false */ /** * If throwFail is set, Y.error will generate or re-throw a JS Error. * Otherwise the failure is logged. * * @property throwFail * @type boolean * @default true */ /** * The window/frame that this instance should operate in. * * @property win * @type Window * @default the window hosting YUI */ /** * The document associated with the 'win' configuration. * * @property doc * @type Document * @default the document hosting YUI */ /** * A list of modules that defines the YUI core (overrides the default). * * @property core * @type string[] */ /** * A list of languages in order of preference. This list is matched against * the list of available languages in modules that the YUI instance uses to * determine the best possible localization of language sensitive modules. * Languages are represented using BCP 47 language tags, such as "en-GB" for * English as used in the United Kingdom, or "zh-Hans-CN" for simplified * Chinese as used in China. The list can be provided as a comma-separated * list or as an array. * * @property lang * @type string|string[] */ /** * The default date format * @property dateFormat * @type string * @deprecated use configuration in DataType.Date.format() instead. */ /** * The default locale * @property locale * @type string * @deprecated use config.lang instead. */ /** * The default interval when polling in milliseconds. * @property pollInterval * @type int * @default 20 */ /** * The number of dynamic nodes to insert by default before * automatically removing them. This applies to script nodes * because remove the node will not make the evaluated script * unavailable. Dynamic CSS is not auto purged, because removing * a linked style sheet will also remove the style definitions. * @property purgethreshold * @type int * @default 20 */ /** * The default interval when polling in milliseconds. * @property windowResizeDelay * @type int * @default 40 */ /** * Base directory for dynamic loading * @property base * @type string */ /* * The secure base dir (not implemented) * For dynamic loading. * @property secureBase * @type string */ /** * The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo? * For dynamic loading. * @property comboBase * @type string */ /** * The root path to prepend to module path for the combo service. * Ex: 3.0.0b1/build/ * For dynamic loading. * @property root * @type string */ /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * * For dynamic loading. * * @property filter * @type string|object */ /** * The 'skin' config let's you configure application level skin * customizations. It contains the following attributes which * can be specified to override the defaults: * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * slider: ['capsule', 'round'] * } * * For dynamic loading. * * @property skin */ /** * Hash of per-component filter specification. If specified for a given * component, this overrides the filter config. * * For dynamic loading. * * @property filters */ /** * Use the YUI combo service to reduce the number of http connections * required to load your dependencies. Turning this off will * disable combo handling for YUI and all module groups configured * with a combo service. * * For dynamic loading. * * @property combine * @type boolean * @default true if 'base' is not supplied, false if it is. */ /** * A list of modules that should never be dynamically loaded * * @property ignore * @type string[] */ /** * A list of modules that should always be loaded when required, even if already * present on the page. * * @property force * @type string[] */ /** * Node or id for a node that should be used as the insertion point for new * nodes. For dynamic loading. * * @property insertBefore * @type string */ /** * Object literal containing attributes to add to dynamically loaded script * nodes. * @property jsAttributes * @type string */ /** * Object literal containing attributes to add to dynamically loaded link * nodes. * @property cssAttributes * @type string */ /** * Number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout. * @property timeout * @type int */ /** * Callback for the 'CSSComplete' event. When dynamically loading YUI * components with CSS, this property fires when the CSS is finished * loading but script loading is still ongoing. This provides an * opportunity to enhance the presentation of a loading page a little * bit before the entire loading process is done. * * @property onCSS * @type function */ /** * A hash of module definitions to add to the list of YUI components. * These components can then be dynamically loaded side by side with * YUI via the use() method. This is a hash, the key is the module * name, and the value is an object literal specifying the metdata * for the module. * See Loader.addModule for the supported module * metadata fields. Also @see groups, which provides a way to * configure the base and combo spec for a set of modules. * <code> * modules: { * &nbsp; mymod1: { * &nbsp; requires: ['node'], * &nbsp; fullpath: 'http://myserver.mydomain.com/mymod1/mymod1.js' * &nbsp; }, * &nbsp; mymod2: { * &nbsp; requires: ['mymod1'], * &nbsp; fullpath: 'http://myserver.mydomain.com/mymod2/mymod2.js' * &nbsp; } * } * </code> * * @property modules * @type object */ /** * A hash of module group definitions. It for each group you * can specify a list of modules and the base path and * combo spec to use when dynamically loading the modules. @see * @see modules for the details about the modules part of the * group definition. * <code> * &nbsp; groups: { * &nbsp; yui2: { * &nbsp; // specify whether or not this group has a combo service * &nbsp; combine: true, * &nbsp; * &nbsp; // the base path for non-combo paths * &nbsp; base: 'http://yui.yahooapis.com/2.8.0r4/build/', * &nbsp; * &nbsp; // the path to the combo service * &nbsp; comboBase: 'http://yui.yahooapis.com/combo?', * &nbsp; * &nbsp; // a fragment to prepend to the path attribute when * &nbsp; // when building combo urls * &nbsp; root: '2.8.0r4/build/', * &nbsp; * &nbsp; // the module definitions * &nbsp; modules: { * &nbsp; yui2_yde: { * &nbsp; path: "yahoo-dom-event/yahoo-dom-event.js" * &nbsp; }, * &nbsp; yui2_anim: { * &nbsp; path: "animation/animation.js", * &nbsp; requires: ['yui2_yde'] * &nbsp; } * &nbsp; } * &nbsp; } * &nbsp; } * </code> * @property modules * @type object */ /** * The loader 'path' attribute to the loader itself. This is combined * with the 'base' attribute to dynamically load the loader component * when boostrapping with the get utility alone. * * @property loaderPath * @type string * @default loader/loader-min.js */ /** * Specifies whether or not YUI().use(...) will attempt to load CSS * resources at all. Any truthy value will cause CSS dependencies * to load when fetching script. The special value 'force' will * cause CSS dependencies to be loaded even if no script is needed. * * @property fetchCSS * @type boolean|string * @default true */ /** * The default gallery version to build gallery module urls * @property gallery * @type string * @since 3.1.0 */ /** * The default YUI 2 version to build yui2 module urls. This is for * intrinsic YUI 2 support via the 2in3 project. Also @see the '2in3' * config for pulling different revisions of the wrapped YUI 2 * modules. * @since 3.1.0 * @property yui2 * @type string * @default 2.8.1 */ /** * The 2in3 project is a deployment of the various versions of YUI 2 * deployed as first-class YUI 3 modules. Eventually, the wrapper * for the modules will change (but the underlying YUI 2 code will * be the same), and you can select a particular version of * the wrapper modules via this config. * @since 3.1.0 * @property 2in3 * @type string * @default 1 */ /** * Alternative console log function for use in environments without * a supported native console. The function is executed in the * YUI instance context. * @since 3.1.0 * @property logFn * @type Function */ /** * A callback to execute when Y.error is called. It receives the * error message and an javascript error object if Y.error was * executed because a javascript error was caught. The function * is executed in the YUI instance context. * * @since 3.2.0 * @property errorFn * @type Function */ /** * A callback to execute when the loader fails to load one or * more resource. This could be because of a script load * failure. It can also fail if a javascript module fails * to register itself, but only when the 'requireRegistration' * is true. If this function is defined, the use() callback will * only be called when the loader succeeds, otherwise it always * executes unless there was a javascript error when attaching * a module. * * @since 3.3.0 * @property loadErrorFn * @type Function */ /** * When set to true, the YUI loader will expect that all modules * it is responsible for loading will be first-class YUI modules * that register themselves with the YUI global. If this is * set to true, loader will fail if the module registration fails * to happen after the script is loaded. * * @since 3.3.0 * @property requireRegistration * @type boolean * @default false */ /** * Cache serviced use() requests. * @since 3.3.0 * @property cacheUse * @type boolean * @default true * @deprecated no longer used */ /** * The parameter defaults for the remote loader service. * Requires the rls submodule. The properties that are * supported: * <pre> * m: comma separated list of module requirements. This * must be the param name even for custom implemetations. * v: the version of YUI to load. Defaults to the version * of YUI that is being used. * gv: the version of the gallery to load (@see the gallery config) * env: comma separated list of modules already on the page. * this must be the param name even for custom implemetations. * lang: the languages supported on the page (@see the lang config) * '2in3v': the version of the 2in3 wrapper to use (@see the 2in3 config). * '2v': the version of yui2 to use in the yui 2in3 wrappers * (@see the yui2 config) * filt: a filter def to apply to the urls (@see the filter config). * filts: a list of custom filters to apply per module * (@see the filters config). * tests: this is a map of conditional module test function id keys * with the values of 1 if the test passes, 0 if not. This must be * the name of the querystring param in custom templates. *</pre> * * @since 3.2.0 * @property rls */ /** * The base path to the remote loader service * * @since 3.2.0 * @property rls_base */ /** * The template to use for building the querystring portion * of the remote loader service url. The default is determined * by the rls config -- each property that has a value will be * represented. * * ex: m={m}&v={v}&env={env}&lang={lang}&filt={filt}&tests={tests} * * * @since 3.2.0 * @property rls_tmpl */ /** * Configure the instance to use a remote loader service instead of * the client loader. * * @since 3.2.0 * @property use_rls */ YUI.add('yui-base', function(Y) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, // If either MooTools or Prototype is on the page, then there's a chance that we // can't trust "native" language features to actually be native. When this is // the case, we take the safe route and fall back to our own non-native // implementation. win = Y.config.win, unsafeNatives = win && !!(win.MooTools || win.Prototype); /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = (!unsafeNatives && Array.isArray) || function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * <p> * Returns a string representing the type of the item passed in. * </p> * * <p> * Known issues: * </p> * * <ul> * <li> * <code>typeof HTMLElementCollection</code> returns function in Safari, but * <code>Y.type()</code> reports object, which could be a good thing -- * but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. * </li> * </ul> * * @method type * @param o the item to test. * @return {string} the detected type. * @static */ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns the current time in milliseconds. * * @method now * @return {int} Current time in milliseconds. * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** * Adds utilities to the YUI instance for working with arrays. Additional array * helpers can be found in the `collection` module. * * @class Array */ /** * `Y.Array(thing)` returns an array created from _thing_. Depending on * _thing_'s type, one of the following will happen: * * * Arrays are returned unmodified unless a non-zero _startIndex_ is * specified. * * Array-like collections (see `Array.test()`) are converted to arrays. * * For everything else, a new array is created with _thing_ as the sole * item. * * Note: elements that are also collections, such as `<form>` and `<select>` * elements, are not automatically converted to arrays. To force a conversion, * pass `true` as the value of the _force_ parameter. * * @method () * @param {mixed} thing The thing to arrayify. * @param {int} [startIndex=0] If non-zero and _thing_ is an array or array-like * collection, a subset of items starting at the specified index will be * returned. * @param {boolean} [force=false] If `true`, _thing_ will be treated as an * array-like collection no matter what. * @return {Array} * @static */ function YArray(thing, startIndex, force) { var len, result; startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** * Evaluates _obj_ to determine if it's an array, an array-like collection, or * something else. This is useful when working with the function `arguments` * collection and `HTMLElement` collections. * * Note: This implementation doesn't consider elements that are also * collections, such as `<form>` and `<select>`, to be array-like. * * @method test * @param {object} obj Object to test. * @return {int} A number indicating the results of the test: * * 0: Neither an array nor an array-like collection. * * 1: Real array. * * 2: Array-like collection. * @static */ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or alert (window), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * Dedupes an array of strings, returning an array that's guaranteed to contain * only one copy of a given string. * * This method differs from `Y.Array.unique` in that it's optimized for use only * with strings, whereas `unique` may be used with other types (but is slower). * Using `dedupe` with non-string values may result in unexpected behavior. * * @method dedupe * @param {String[]} array Array of strings to dedupe. * @return {Array} Deduped copy of _array_. * @static * @since 3.4.0 */ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** * Executes the supplied function on each item in the array. This method wraps * the native ES5 `Array.forEach()` method if available. * * @method each * @param {Array} array Array to iterate. * @param {Function} fn Function to execute on each item in the array. * @param {mixed} fn.item Current array item. * @param {Number} fn.index Current array index. * @param {Array} fn.array Array being iterated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @return {YUI} The YUI instance. * @chainable * @static */ YArray.each = YArray.forEach = Native.forEach ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** * Alias for `each`. * * @method forEach * @static */ /** * Returns an object using the first array as keys and the second as values. If * the second array is not provided, or if it doesn't contain the same number of * values as the first array, then `true` will be used in place of the missing * values. * * @example * * Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); * // => {a: 'foo', b: 'bar', c: true} * * @method hash * @param {Array} keys Array to use as keys. * @param {Array} [values] Array to use as values. * @return {Object} * @static */ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** * Returns the index of the first item in the array that's equal (using a strict * equality check) to the specified _value_, or `-1` if the value isn't found. * * This method wraps the native ES5 `Array.indexOf()` method if available. * * @method indexOf * @param {Array} array Array to search. * @param {any} value Value to search for. * @return {Number} Index of the item strictly equal to _value_, or `-1` if not * found. * @static */ YArray.indexOf = Native.indexOf ? function (array, value) { // TODO: support fromIndex return Native.indexOf.call(array, value); } : function (array, value) { for (var i = 0, len = array.length; i < len; ++i) { if (array[i] === value) { return i; } } return -1; }; /** * Numeric sort convenience function. * * The native `Array.prototype.sort()` function converts values to strings and * sorts them in lexicographic order, which is unsuitable for sorting numeric * values. Provide `Y.Array.numericSort` as a custom sort function when you want * to sort values in numeric order. * * @example * * [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); * // => [4, 8, 15, 16, 23, 42] * * @method numericSort * @param {Number} a First value to compare. * @param {Number} b Second value to compare. * @return {Number} Difference between _a_ and _b_. * @static */ YArray.numericSort = function (a, b) { return a - b; }; /** * Executes the supplied function on each item in the array. Returning a truthy * value from the function will stop the processing of remaining items. * * @method some * @param {Array} array Array to iterate. * @param {Function} fn Function to execute on each item. * @param {mixed} fn.value Current array item. * @param {Number} fn.index Current array index. * @param {Array} fn.array Array being iterated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @return {Boolean} `true` if the function returns a truthy value on any of the * items in the array; `false` otherwise. * @static */ YArray.some = Native.some ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : arg.toString(); if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var args = arguments, i = 0, len = args.length, result = {}; for (; i < len; ++i) { Y.mix(result, args[i], true); } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties will not be overwritten or merged unless the _overwrite_ or _merge_ parameters are `true`, respectively. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Int} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a call // to `hasOwnProperty` on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } exists = alwaysOverwrite ? false : hasOwn.call(to, key); if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } exists = alwaysOverwrite ? false : hasOwn.call(to, key); if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var hasOwn = Object.prototype.hasOwnProperty, // If either MooTools or Prototype is on the page, then there's a chance that we // can't trust "native" language features to actually be native. When this is // the case, we take the safe route and fall back to our own non-native // implementations. win = Y.config.win, unsafeNatives = win && !!(win.MooTools || win.Prototype), UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = (!unsafeNatives && Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type {Boolean} * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = (!unsafeNatives && Object.keys) || function (obj) { if (!Y.Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; for (key in obj) { if (owns(obj, key)) { keys.push(key); } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { return O.keys(obj).length; }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Y.Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(obj).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method for parsing the UA string. Defaults to assigning it's value to Y.UA * @static * @method Env.parseUA * @param {String} subUA Parse this UA string instead of navigator.userAgent * @returns {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh/i).test(ua)) { o.os = 'macintosh'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } } m = ua.match(/Chrome\/([^\s]*)/); if (m && m[1]) { o.chrome = numberify(m[1]); // Chrome o.safari = 0; //Reset safari back to 0 } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } YUI.Env.UA = o; return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "app": ["controller","model","model-list","view"], "attribute": ["attribute-base","attribute-complex"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-base","datatable-datasource","datatable-sort","datatable-scroll"], "datatype": ["datatype-number","datatype-date","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "text": ["text-accentfold","text-wordbreak"], "transition": ["transition-native","transition-timer"], "widget": ["widget-base","widget-htmlparser","widget-uievents","widget-skin"], "yui-rls": ["yui-base","get","features","intl-base","rls","yui-log","yui-later"] }; }, '@VERSION@' ); YUI.add('get', function(Y) { /** * Provides a mechanism to fetch remote resources and * insert them into a document. * @module yui * @submodule get */ /** * Fetches and inserts one or more script or link nodes into the document * @class Get * @static */ var ua = Y.UA, L = Y.Lang, TYPE_JS = 'text/javascript', TYPE_CSS = 'text/css', STYLESHEET = 'stylesheet', SCRIPT = 'script', AUTOPURGE = 'autopurge', UTF8 = 'utf-8', LINK = 'link', ASYNC = 'async', ALL = true, // FireFox does not support the onload event for link nodes, so // there is no way to make the css requests synchronous. This means // that the css rules in multiple files could be applied out of order // in this browser if a later request returns before an earlier one. // Safari too. ONLOAD_SUPPORTED = { script: ALL, css: !(ua.webkit || ua.gecko) }, /** * hash of queues to manage multiple requests * @property queues * @private */ queues = {}, /** * queue index used to generate transaction ids * @property qidx * @type int * @private */ qidx = 0, /** * interal property used to prevent multiple simultaneous purge * processes * @property purging * @type boolean * @private */ purging, /** * Clear timeout state * * @method _clearTimeout * @param {Object} q Queue data * @private */ _clearTimeout = function(q) { var timer = q.timer; if (timer) { clearTimeout(timer); q.timer = null; } }, /** * Generates an HTML element, this is not appended to a document * @method _node * @param {string} type the type of element. * @param {Object} attr the fixed set of attribute for the type. * @param {Object} custAttrs optional Any custom attributes provided by the user. * @param {Window} win optional window to create the element in. * @return {HTMLElement} the generated node. * @private */ _node = function(type, attr, custAttrs, win) { var w = win || Y.config.win, d = w.document, n = d.createElement(type), i; if (custAttrs) { Y.mix(attr, custAttrs); } for (i in attr) { if (attr[i] && attr.hasOwnProperty(i)) { n.setAttribute(i, attr[i]); } } return n; }, /** * Generates a link node * @method _linkNode * @param {string} url the url for the css file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _linkNode = function(url, win, attributes) { return _node(LINK, { id: Y.guid(), type: TYPE_CSS, rel: STYLESHEET, href: url }, attributes, win); }, /** * Generates a script node * @method _scriptNode * @param {string} url the url for the script file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _scriptNode = function(url, win, attributes) { return _node(SCRIPT, { id: Y.guid(), type: TYPE_JS, src: url }, attributes, win); }, /** * Returns the data payload for callback functions. * @method _returnData * @param {object} q the queue. * @param {string} msg the result message. * @param {string} result the status message from the request. * @return {object} the state data from the request. * @private */ _returnData = function(q, msg, result) { return { tId: q.tId, win: q.win, data: q.data, nodes: q.nodes, msg: msg, statusText: result, purge: function() { _purge(this.tId); } }; }, /** * The transaction is finished * @method _end * @param {string} id the id of the request. * @param {string} msg the result message. * @param {string} result the status message from the request. * @private */ _end = function(id, msg, result) { var q = queues[id], onEnd = q && q.onEnd; q.finished = true; if (onEnd) { onEnd.call(q.context, _returnData(q, msg, result)); } }, /** * The request failed, execute fail handler with whatever * was accomplished. There isn't a failure case at the * moment unless you count aborted transactions * @method _fail * @param {string} id the id of the request * @private */ _fail = function(id, msg) { var q = queues[id], onFailure = q.onFailure; _clearTimeout(q); if (onFailure) { onFailure.call(q.context, _returnData(q, msg)); } _end(id, msg, 'failure'); }, /** * Abort the transaction * * @method _abort * @param {Object} id * @private */ _abort = function(id) { _fail(id, 'transaction ' + id + ' was aborted'); }, /** * The request is complete, so executing the requester's callback * @method _complete * @param {string} id the id of the request. * @private */ _complete = function(id) { var q = queues[id], onSuccess = q.onSuccess; _clearTimeout(q); if (q.aborted) { _abort(id); } else { if (onSuccess) { onSuccess.call(q.context, _returnData(q)); } // 3.3.0 had undefined msg for this path. _end(id, undefined, 'OK'); } }, /** * Get node reference, from string * * @method _getNodeRef * @param {String|HTMLElement} nId The node id to find. If an HTMLElement is passed in, it will be returned. * @param {String} tId Queue id, used to determine document for queue * @private */ _getNodeRef = function(nId, tId) { var q = queues[tId], n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId; if (!n) { _fail(tId, 'target node not found: ' + nId); } return n; }, /** * Removes the nodes for the specified queue * @method _purge * @param {string} tId the transaction id. * @private */ _purge = function(tId) { var nodes, doc, parent, sibling, node, attr, insertBefore, i, l, q = queues[tId]; if (q) { nodes = q.nodes; l = nodes.length; // TODO: Why is node.parentNode undefined? Which forces us to do this... /* doc = q.win.document; parent = doc.getElementsByTagName('head')[0]; insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0]; if (insertBefore) { sibling = _getNodeRef(insertBefore, tId); if (sibling) { parent = sibling.parentNode; } } */ for (i = 0; i < l; i++) { node = nodes[i]; parent = node.parentNode; if (node.clearAttributes) { node.clearAttributes(); } else { // This destroys parentNode ref, so we hold onto it above first. for (attr in node) { if (node.hasOwnProperty(attr)) { delete node[attr]; } } } parent.removeChild(node); } } q.nodes = []; }, /** * Progress callback * * @method _progress * @param {string} id The id of the request. * @param {string} The url which just completed. * @private */ _progress = function(id, url) { var q = queues[id], onProgress = q.onProgress, o; if (onProgress) { o = _returnData(q); o.url = url; onProgress.call(q.context, o); } }, /** * Timeout detected * @method _timeout * @param {string} id the id of the request. * @private */ _timeout = function(id) { var q = queues[id], onTimeout = q.onTimeout; if (onTimeout) { onTimeout.call(q.context, _returnData(q)); } _end(id, 'timeout', 'timeout'); }, /** * onload callback * @method _loaded * @param {string} id the id of the request. * @return {string} the result. * @private */ _loaded = function(id, url) { var q = queues[id], sync = !q.async; if (sync) { _clearTimeout(q); } _progress(id, url); // TODO: Cleaning up flow to have a consistent end point // !q.finished check is for the async case, // where scripts may still be loading when we've // already aborted. Ideally there should be a single path // for this. if (!q.finished) { if (q.aborted) { _abort(id); } else { if ((--q.remaining) === 0) { _complete(id); } else if (sync) { _next(id); } } } }, /** * Detects when a node has been loaded. In the case of * script nodes, this does not guarantee that contained * script is ready to use. * @method _trackLoad * @param {string} type the type of node to track. * @param {HTMLElement} n the node to track. * @param {string} id the id of the request. * @param {string} url the url that is being loaded. * @private */ _trackLoad = function(type, n, id, url) { // TODO: Can we massage this to use ONLOAD_SUPPORTED[type]? // IE supports the readystatechange event for script and css nodes // Opera only for script nodes. Opera support onload for script // nodes, but this doesn't fire when there is a load failure. // The onreadystatechange appears to be a better way to respond // to both success and failure. if (ua.ie) { n.onreadystatechange = function() { var rs = this.readyState; if ('loaded' === rs || 'complete' === rs) { n.onreadystatechange = null; _loaded(id, url); } }; } else if (ua.webkit) { // webkit prior to 3.x is no longer supported if (type === SCRIPT) { // Safari 3.x supports the load event for script nodes (DOM2) n.addEventListener('load', function() { _loaded(id, url); }, false); } } else { // FireFox and Opera support onload (but not DOM2 in FF) handlers for // script nodes. Opera, but not FF, supports the onload event for link nodes. n.onload = function() { _loaded(id, url); }; n.onerror = function(e) { _fail(id, e + ': ' + url); }; } }, _insertInDoc = function(node, id, win) { // Add it to the head or insert it before 'insertBefore'. // Work around IE bug if there is a base tag. var q = queues[id], doc = win.document, insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0], sibling; if (insertBefore) { sibling = _getNodeRef(insertBefore, id); if (sibling) { sibling.parentNode.insertBefore(node, sibling); } } else { // 3.3.0 assumed head is always around. doc.getElementsByTagName('head')[0].appendChild(node); } }, /** * Loads the next item for a given request * @method _next * @param {string} id the id of the request. * @return {string} the result. * @private */ _next = function(id) { // Assigning out here for readability var q = queues[id], type = q.type, attrs = q.attributes, win = q.win, timeout = q.timeout, node, url; if (q.url.length > 0) { url = q.url.shift(); // !q.timer ensures that this only happens once for async if (timeout && !q.timer) { q.timer = setTimeout(function() { _timeout(id); }, timeout); } if (type === SCRIPT) { node = _scriptNode(url, win, attrs); } else { node = _linkNode(url, win, attrs); } // add the node to the queue so we can return it in the callback q.nodes.push(node); _trackLoad(type, node, id, url); _insertInDoc(node, id, win); if (!ONLOAD_SUPPORTED[type]) { _loaded(id, url); } if (q.async) { // For sync, the _next call is chained in _loaded _next(id); } } }, /** * Removes processed queues and corresponding nodes * @method _autoPurge * @private */ _autoPurge = function() { if (purging) { return; } purging = true; var i, q; for (i in queues) { if (queues.hasOwnProperty(i)) { q = queues[i]; if (q.autopurge && q.finished) { _purge(q.tId); delete queues[i]; } } } purging = false; }, /** * Saves the state for the request and begins loading * the requested urls * @method queue * @param {string} type the type of node to insert. * @param {string} url the url to load. * @param {object} opts the hash of options for this request. * @return {object} transaction object. * @private */ _queue = function(type, url, opts) { opts = opts || {}; var id = 'q' + (qidx++), thresh = opts.purgethreshold || Y.Get.PURGE_THRESH, q; if (qidx % thresh === 0) { _autoPurge(); } // Merge to protect opts (grandfathered in). q = queues[id] = Y.merge(opts); // Avoid mix, merge overhead. Known set of props. q.tId = id; q.type = type; q.url = url; q.finished = false; q.nodes = []; q.win = q.win || Y.config.win; q.context = q.context || q; q.autopurge = (AUTOPURGE in q) ? q.autopurge : (type === SCRIPT) ? true : false; q.attributes = q.attributes || {}; q.attributes.charset = opts.charset || q.attributes.charset || UTF8; if (ASYNC in q && type === SCRIPT) { q.attributes.async = q.async; } q.url = (L.isString(q.url)) ? [q.url] : q.url; // TODO: Do we really need to account for this developer error? // If the url is undefined, this is probably a trailing comma problem in IE. if (!q.url[0]) { q.url.shift(); } q.remaining = q.url.length; _next(id); return { tId: id }; }; Y.Get = { /** * The number of request required before an automatic purge. * Can be configured via the 'purgethreshold' config * property PURGE_THRESH * @static * @type int * @default 20 * @private */ PURGE_THRESH: 20, /** * Abort a transaction * @method abort * @static * @param {string|object} o Either the tId or the object returned from * script() or css(). */ abort : function(o) { var id = (L.isString(o)) ? o : o.tId, q = queues[id]; if (q) { q.aborted = true; } }, /** * Fetches and inserts one or more script nodes into the head * of the current document or the document in a specified window. * * @method script * @static * @param {string|string[]} url the url or urls to the script(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the script(s) are finished loading * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onTimeout</dt> * <dd> * callback to execute when a timeout occurs. * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onEnd</dt> * <dd>a function that executes when the transaction finishes, * regardless of the exit path</dd> * <dt>onFailure</dt> * <dd> * callback to execute when the script load operation fails * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted successfully</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove any nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onProgress</dt> * <dd>callback to execute when each individual file is done loading * (useful when passing in an array of js files). Receives the same * payload as onSuccess, with the addition of a <code>url</code> * property, which identifies the file which was loaded.</dd> * <dt>async</dt> * <dd> * <p>When passing in an array of JS files, setting this flag to true * will insert them into the document in parallel, as opposed to the * default behavior, which is to chain load them serially. It will also * set the async attribute on the script node to true.</p> * <p>Setting async:true * will lead to optimal file download performance allowing the browser to * download multiple scripts in parallel, and execute them as soon as they * are available.</p> * <p>Note that async:true does not guarantee execution order of the * scripts being downloaded. They are executed in whichever order they * are received.</p> * </dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>autopurge</dt> * <dd> * setting to true will let the utilities cleanup routine purge * the script once loaded * </dd> * <dt>purgethreshold</dt> * <dd> * The number of transaction before autopurge should be initiated * </dd> * <dt>data</dt> * <dd> * data that is supplied to the callback when the script(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling. * If this is not specified, nodes will be inserted before a base * tag should it exist. Otherwise, the nodes will be appended to the * end of the document head.</dd> * </dl> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * <dt>timeout</dt> * <dd>Number of milliseconds to wait before aborting and firing * the timeout event</dd> * <pre> * &nbsp; Y.Get.script( * &nbsp; ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js", * &nbsp; "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], * &nbsp; &#123; * &nbsp; onSuccess: function(o) &#123; * &nbsp; this.log("won't cause error because Y is the context"); * &nbsp; // immediately * &nbsp; &#125;, * &nbsp; onFailure: function(o) &#123; * &nbsp; &#125;, * &nbsp; onTimeout: function(o) &#123; * &nbsp; &#125;, * &nbsp; data: "foo", * &nbsp; timeout: 10000, // 10 second timeout * &nbsp; context: Y, // make the YUI instance * &nbsp; // win: otherframe // target another window/frame * &nbsp; autopurge: true // allow the utility to choose when to * &nbsp; // remove the nodes * &nbsp; purgetheshold: 1 // purge previous transaction before * &nbsp; // next transaction * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ script: function(url, opts) { return _queue(SCRIPT, url, opts); }, /** * Fetches and inserts one or more css link nodes into the * head of the current document or the document in a specified * window. * @method css * @static * @param {string} url the url or urls to the css file(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the css file(s) are finished loading * The callback receives an object back with the following * data: * <dl>win</dl> * <dd>the window the link nodes(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onProgress</dt> * <dd>callback to execute when each individual file is done loading (useful when passing in an array of css files). Receives the same * payload as onSuccess, with the addition of a <code>url</code> property, which identifies the file which was loaded. Currently only useful for non Webkit/Gecko browsers, * where onload for css is detected accurately.</dd> * <dt>async</dt> * <dd>When passing in an array of css files, setting this flag to true will insert them * into the document in parallel, as oppposed to the default behavior, which is to chain load them (where possible). * This flag is more useful for scripts currently, since for css Get only chains if not Webkit/Gecko.</dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>data</dt> * <dd> * data that is supplied to the callbacks when the nodes(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling</dd> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * </dl> * <pre> * Y.Get.css("http://localhost/css/menu.css"); * </pre> * <pre> * &nbsp; Y.Get.css( * &nbsp; ["http://localhost/css/menu.css", * &nbsp; insertBefore: 'custom-styles' // nodes will be inserted * &nbsp; // before the specified node * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ css: function(url, opts) { return _queue('css', url, opts); } }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; Y.mix(Y.namespace('Features'), { tests: feature_tests, add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/meta_join.py */ var add = Y.Features.add; // graphics-svg.js add('load', '0', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }); // ie-base-test.js add('load', '1', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-vml.js add('load', '2', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT.createElement("canvas"); return (!DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // ie-style-test.js add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // 0 add('load', '4', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // autocomplete-list-keys-sniff.js add('load', '5', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // graphics-canvas.js add('load', '6', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT.createElement("canvas"); return (!DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }); // dd-gestures-test.js add('load', '7', { "name": "dd-gestures", "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }); // selector-test.js add('load', '8', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // history-hash-ie-test.js add('load', '9', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('intl-base', function(Y) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-later', function(Y) { /** * Provides a setTimeout/setInterval wrapper * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @method later * @for YUI * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : data; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('loader-base', function(Y) { /** * The YUI loader core * @module loader * @submodule loader-base */ if (!YUI.Env[Y.version]) { (function() { var VERSION = Y.version, BUILD = '/build/', ROOT = VERSION + BUILD, CDN_BASE = Y.Env.base, GALLERY_VERSION = 'gallery-2011.06.08-20-04', TNT = '2in3', TNT_VERSION = '4', YUI2_VERSION = '2.9.0', COMBO_BASE = CDN_BASE + 'combo?', META = { version: VERSION, root: ROOT, base: Y.Env.base, comboBase: COMBO_BASE, skin: { defaultSkin: 'sam', base: 'assets/skins/', path: 'skin.css', after: ['cssreset', 'cssfonts', 'cssgrids', 'cssbase', 'cssreset-context', 'cssfonts-context']}, groups: {}, patterns: {} }, groups = META.groups, yui2Update = function(tnt, yui2) { var root = TNT + '.' + (tnt || TNT_VERSION) + '/' + (yui2 || YUI2_VERSION) + BUILD; groups.yui2.base = CDN_BASE + root; groups.yui2.root = root; }, galleryUpdate = function(tag) { var root = (tag || GALLERY_VERSION) + BUILD; groups.gallery.base = CDN_BASE + root; groups.gallery.root = root; }; groups[VERSION] = {}; groups.gallery = { ext: false, combine: true, comboBase: COMBO_BASE, update: galleryUpdate, patterns: { 'gallery-': { }, 'lang/gallery-': {}, 'gallerycss-': { type: 'css' } } }; groups.yui2 = { combine: true, ext: false, comboBase: COMBO_BASE, update: yui2Update, patterns: { 'yui2-': { configFn: function(me) { if (/-skin|reset|fonts|grids|base/.test(me.name)) { me.type = 'css'; me.path = me.path.replace(/\.js/, '.css'); // this makes skins in builds earlier than // 2.6.0 work as long as combine is false me.path = me.path.replace(/\/yui2-skin/, '/assets/skins/sam/yui2-skin'); } } } } }; galleryUpdate(); yui2Update(); YUI.Env[VERSION] = META; }()); } /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * @module loader * @submodule loader-base */ var NOT_FOUND = {}, NO_REQUIREMENTS = [], MAX_URL_LENGTH = (Y.UA.ie) ? 2048 : 8192, GLOBAL_ENV = YUI.Env, GLOBAL_LOADED = GLOBAL_ENV._loaded, CSS = 'css', JS = 'js', INTL = 'intl', VERSION = Y.version, ROOT_LANG = '', YObject = Y.Object, oeach = YObject.each, YArray = Y.Array, _queue = GLOBAL_ENV._loaderQueue, META = GLOBAL_ENV[VERSION], SKIN_PREFIX = 'skin-', L = Y.Lang, ON_PAGE = GLOBAL_ENV.mods, modulekey, cache, _path = function(dir, file, type, nomin) { var path = dir + '/' + file; if (!nomin) { path += '-min'; } path += '.' + (type || CSS); return path; }; /** * The component metadata is stored in Y.Env.meta. * Part of the loader module. * @property Env.meta * @for YUI */ Y.Env.meta = META; /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * While the loader can be instantiated by the end user, it normally is not. * @see YUI.use for the normal use case. The use function automatically will * pull in missing dependencies. * * @constructor * @class Loader * @param {object} o an optional set of configuration options. Valid options: * <ul> * <li>base: * The base dir</li> * <li>comboBase: * The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li> * <li>root: * The root path to prepend to module names for the combo service. * Ex: 2.5.2/build/</li> * <li>filter:. * * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * * </li> * <li>filters: per-component filter specification. If specified * for a given component, this overrides the filter config</li> * <li>combine: * Use the YUI combo service to reduce the number of http connections * required to load your dependencies</li> * <li>ignore: * A list of modules that should never be dynamically loaded</li> * <li>force: * A list of modules that should always be loaded when required, even if * already present on the page</li> * <li>insertBefore: * Node or id for a node that should be used as the insertion point for * new nodes</li> * <li>charset: * charset for dynamic nodes (deprecated, use jsAttributes or cssAttributes) * </li> * <li>jsAttributes: object literal containing attributes to add to script * nodes</li> * <li>cssAttributes: object literal containing attributes to add to link * nodes</li> * <li>timeout: * The number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout</li> * <li>context: * execution context for all callbacks</li> * <li>onSuccess: * callback for the 'success' event</li> * <li>onFailure: callback for the 'failure' event</li> * <li>onCSS: callback for the 'CSSComplete' event. When loading YUI * components with CSS the CSS is loaded first, then the script. This * provides a moment you can tie into to improve * the presentation of the page while the script is loading.</li> * <li>onTimeout: * callback for the 'timeout' event</li> * <li>onProgress: * callback executed each time a script or css file is loaded</li> * <li>modules: * A list of module definitions. See Loader.addModule for the supported * module metadata</li> * <li>groups: * A list of group definitions. Each group can contain specific definitions * for base, comboBase, combine, and accepts a list of modules. See above * for the description of these properties.</li> * <li>2in3: the version of the YUI 2 in 3 wrapper to use. The intrinsic * support for YUI 2 modules in YUI 3 relies on versions of the YUI 2 * components inside YUI 3 module wrappers. These wrappers * change over time to accomodate the issues that arise from running YUI 2 * in a YUI 3 sandbox.</li> * <li>yui2: when using the 2in3 project, you can select the version of * YUI 2 to use. Valid values * are 2.2.2, 2.3.1, 2.4.1, 2.5.2, 2.6.0, * 2.7.0, 2.8.0, and 2.8.1 [default] -- plus all versions of YUI 2 * going forward.</li> * </ul> */ Y.Loader = function(o) { var defaults = META.modules, self = this; modulekey = META.md5; /** * Internal callback to handle multiple internal insert() calls * so that css is inserted prior to js * @property _internalCallback * @private */ // self._internalCallback = null; /** * Callback that will be executed when the loader is finished * with an insert * @method onSuccess * @type function */ // self.onSuccess = null; /** * Callback that will be executed if there is a failure * @method onFailure * @type function */ // self.onFailure = null; /** * Callback for the 'CSSComplete' event. When loading YUI components * with CSS the CSS is loaded first, then the script. This provides * a moment you can tie into to improve the presentation of the page * while the script is loading. * @method onCSS * @type function */ // self.onCSS = null; /** * Callback executed each time a script or css file is loaded * @method onProgress * @type function */ // self.onProgress = null; /** * Callback that will be executed if a timeout occurs * @method onTimeout * @type function */ // self.onTimeout = null; /** * The execution context for all callbacks * @property context * @default {YUI} the YUI instance */ self.context = Y; /** * Data that is passed to all callbacks * @property data */ // self.data = null; /** * Node reference or id where new nodes should be inserted before * @property insertBefore * @type string|HTMLElement */ // self.insertBefore = null; /** * The charset attribute for inserted nodes * @property charset * @type string * @deprecated , use cssAttributes or jsAttributes. */ // self.charset = null; /** * An object literal containing attributes to add to link nodes * @property cssAttributes * @type object */ // self.cssAttributes = null; /** * An object literal containing attributes to add to script nodes * @property jsAttributes * @type object */ // self.jsAttributes = null; /** * The base directory. * @property base * @type string * @default http://yui.yahooapis.com/[YUI VERSION]/build/ */ self.base = Y.Env.meta.base; /** * Base path for the combo service * @property comboBase * @type string * @default http://yui.yahooapis.com/combo? */ self.comboBase = Y.Env.meta.comboBase; /* * Base path for language packs. */ // self.langBase = Y.Env.meta.langBase; // self.lang = ""; /** * If configured, the loader will attempt to use the combo * service for YUI resources and configured external resources. * @property combine * @type boolean * @default true if a base dir isn't in the config */ self.combine = o.base && (o.base.indexOf(self.comboBase.substr(0, 20)) > -1); /** * Max url length for combo urls. The default is 2048 for * internet explorer, and 8192 otherwise. This is the URL * limit for the Yahoo! hosted combo servers. If consuming * a different combo service that has a different URL limit * it is possible to override this default by supplying * the maxURLLength config option. The config option will * only take effect if lower than the default. * * Browsers: * IE: 2048 * Other A-Grade Browsers: Higher that what is typically supported * 'capable' mobile browsers: * * Servers: * Apache: 8192 * * @property maxURLLength * @type int */ self.maxURLLength = MAX_URL_LENGTH; /** * Ignore modules registered on the YUI global * @property ignoreRegistered * @default false */ // self.ignoreRegistered = false; /** * Root path to prepend to module path for the combo * service * @property root * @type string * @default [YUI VERSION]/build/ */ self.root = Y.Env.meta.root; /** * Timeout value in milliseconds. If set, self value will be used by * the get utility. the timeout event will fire if * a timeout occurs. * @property timeout * @type int */ self.timeout = 0; /** * A list of modules that should not be loaded, even if * they turn up in the dependency tree * @property ignore * @type string[] */ // self.ignore = null; /** * A list of modules that should always be loaded, even * if they have already been inserted into the page. * @property force * @type string[] */ // self.force = null; self.forceMap = {}; /** * Should we allow rollups * @property allowRollup * @type boolean * @default false */ self.allowRollup = false; /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * @property filter * @type string| {searchExp: string, replaceStr: string} */ // self.filter = null; /** * per-component filter specification. If specified for a given * component, this overrides the filter config. * @property filters * @type object */ self.filters = {}; /** * The list of requested modules * @property required * @type {string: boolean} */ self.required = {}; /** * If a module name is predefined when requested, it is checked againsts * the patterns provided in this property. If there is a match, the * module is added with the default configuration. * * At the moment only supporting module prefixes, but anticipate * supporting at least regular expressions. * @property patterns * @type Object */ // self.patterns = Y.merge(Y.Env.meta.patterns); self.patterns = {}; /** * The library metadata * @property moduleInfo */ // self.moduleInfo = Y.merge(Y.Env.meta.moduleInfo); self.moduleInfo = {}; self.groups = Y.merge(Y.Env.meta.groups); /** * Provides the information used to skin the skinnable components. * The following skin definition would result in 'skin1' and 'skin2' * being loaded for calendar (if calendar was requested), and * 'sam' for all other skinnable components: * * <code> * skin: { * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. ex: * // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/ * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * calendar: ['skin1', 'skin2'] * } * } * </code> * @property skin */ self.skin = Y.merge(Y.Env.meta.skin); /* * Map of conditional modules * @since 3.2.0 */ self.conditions = {}; // map of modules with a hash of modules that meet the requirement // self.provides = {}; self.config = o; self._internal = true; cache = GLOBAL_ENV._renderedMods; if (cache) { oeach(cache, function modCache(v, k) { //self.moduleInfo[k] = Y.merge(v); self.moduleInfo[k] = v; }); cache = GLOBAL_ENV._conditions; oeach(cache, function condCache(v, k) { //self.conditions[k] = Y.merge(v); self.conditions[k] = v; }); } else { oeach(defaults, self.addModule, self); } if (!GLOBAL_ENV._renderedMods) { //GLOBAL_ENV._renderedMods = Y.merge(self.moduleInfo); //GLOBAL_ENV._conditions = Y.merge(self.conditions); GLOBAL_ENV._renderedMods = self.moduleInfo; GLOBAL_ENV._conditions = self.conditions; } self._inspectPage(); self._internal = false; self._config(o); self.testresults = null; if (Y.config.tests) { self.testresults = Y.config.tests; } /** * List of rollup files found in the library metadata * @property rollups */ // self.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ // self.loadOptional = false; /** * All of the derived dependencies in sorted order, which * will be populated when either calculate() or insert() * is called * @property sorted * @type string[] */ self.sorted = []; /** * Set when beginning to compute the dependency tree. * Composed of what YUI reports to be loaded combined * with what has been loaded by any instance on the page * with the version number specified in the metadata. * @property loaded * @type {string: boolean} */ self.loaded = GLOBAL_LOADED[VERSION]; /* * A list of modules to attach to the YUI instance when complete. * If not supplied, the sorted list of dependencies are applied. * @property attaching */ // self.attaching = null; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ self.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ self.inserted = {}; /** * List of skipped modules during insert() because the module * was not defined * @property skipped */ self.skipped = {}; // Y.on('yui:load', self.loadNext, self); self.tested = {}; /* * Cached sorted calculate results * @property results * @since 3.2.0 */ //self.results = {}; }; Y.Loader.prototype = { FILTER_DEFS: { RAW: { 'searchExp': '-min\\.js', 'replaceStr': '.js' }, DEBUG: { 'searchExp': '-min\\.js', 'replaceStr': '-debug.js' } }, _inspectPage: function() { oeach(ON_PAGE, function(v, k) { if (v.details) { var m = this.moduleInfo[k], req = v.details.requires, mr = m && m.requires; if (m) { if (!m._inspected && req && mr.length != req.length) { // console.log('deleting ' + m.name); // m.requres = YObject.keys(Y.merge(YArray.hash(req), YArray.hash(mr))); delete m.expanded; // delete m.expanded_map; } } else { m = this.addModule(v.details, k); } m._inspected = true; } }, this); }, // returns true if b is not loaded, and is required // directly or by means of modules it supersedes. _requires: function(mod1, mod2) { var i, rm, after_map, s, info = this.moduleInfo, m = info[mod1], other = info[mod2]; if (!m || !other) { return false; } rm = m.expanded_map; after_map = m.after_map; // check if this module should be sorted after the other // do this first to short circut circular deps if (after_map && (mod2 in after_map)) { return true; } after_map = other.after_map; // and vis-versa if (after_map && (mod1 in after_map)) { return false; } // check if this module requires one the other supersedes s = info[mod2] && info[mod2].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod1, s[i])) { return true; } } } s = info[mod1] && info[mod1].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod2, s[i])) { return false; } } } // check if this module requires the other directly // if (r && YArray.indexOf(r, mod2) > -1) { if (rm && (mod2 in rm)) { return true; } // external css files should be sorted below yui css if (m.ext && m.type == CSS && !other.ext && other.type == CSS) { return true; } return false; }, _config: function(o) { var i, j, val, f, group, groupName, self = this; // apply config values if (o) { for (i in o) { if (o.hasOwnProperty(i)) { val = o[i]; if (i == 'require') { self.require(val); } else if (i == 'skin') { Y.mix(self.skin, o[i], true); } else if (i == 'groups') { for (j in val) { if (val.hasOwnProperty(j)) { groupName = j; group = val[j]; self.addGroup(group, groupName); } } } else if (i == 'modules') { // add a hash of module definitions oeach(val, self.addModule, self); } else if (i == 'gallery') { this.groups.gallery.update(val); } else if (i == 'yui2' || i == '2in3') { this.groups.yui2.update(o['2in3'], o.yui2); } else if (i == 'maxURLLength') { self[i] = Math.min(MAX_URL_LENGTH, val); } else { self[i] = val; } } } } // fix filter f = self.filter; if (L.isString(f)) { f = f.toUpperCase(); self.filterName = f; self.filter = self.FILTER_DEFS[f]; if (f == 'DEBUG') { self.require('yui-log', 'dump'); } } if (self.lang) { self.require('intl-base', 'intl'); } }, /** * Returns the skin module name for the specified skin name. If a * module name is supplied, the returned skin module name is * specific to the module passed in. * @method formatSkin * @param {string} skin the name of the skin. * @param {string} mod optional: the name of a module to skin. * @return {string} the full skin module name. */ formatSkin: function(skin, mod) { var s = SKIN_PREFIX + skin; if (mod) { s = s + '-' + mod; } return s; }, /** * Adds the skin def to the module info * @method _addSkin * @param {string} skin the name of the skin. * @param {string} mod the name of the module. * @param {string} parent parent module if this is a skin of a * submodule or plugin. * @return {string} the module name for the skin. * @private */ _addSkin: function(skin, mod, parent) { var mdef, pkg, name, nmod, info = this.moduleInfo, sinf = this.skin, ext = info[mod] && info[mod].ext; // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!info[name]) { mdef = info[mod]; pkg = mdef.pkg || mod; nmod = { name: name, group: mdef.group, type: 'css', after: sinf.after, path: (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css', ext: ext }; if (mdef.base) { nmod.base = mdef.base; } if (mdef.configFn) { nmod.configFn = mdef.configFn; } this.addModule(nmod, name); } } return name; }, /** * Add a new module group * <dl> * <dt>name:</dt> <dd>required, the group name</dd> * <dt>base:</dt> <dd>The base dir for this module group</dd> * <dt>root:</dt> <dd>The root path to add to each combo * resource path</dd> * <dt>combine:</dt> <dd>combo handle</dd> * <dt>comboBase:</dt> <dd>combo service base path</dd> * <dt>modules:</dt> <dd>the group of modules</dd> * </dl> * @method addGroup * @param {object} o An object containing the module data. * @param {string} name the group name. */ addGroup: function(o, name) { var mods = o.modules, self = this; name = name || o.name; o.name = name; self.groups[name] = o; if (o.patterns) { oeach(o.patterns, function(v, k) { v.group = name; self.patterns[k] = v; }); } if (mods) { oeach(mods, function(v, k) { v.group = name; self.addModule(v, k); }, self); } }, /** * Add a new module to the component metadata. * <dl> * <dt>name:</dt> <dd>required, the component name</dd> * <dt>type:</dt> <dd>required, the component type (js or css) * </dd> * <dt>path:</dt> <dd>required, the path to the script from * "base"</dd> * <dt>requires:</dt> <dd>array of modules required by this * component</dd> * <dt>optional:</dt> <dd>array of optional modules for this * component</dd> * <dt>supersedes:</dt> <dd>array of the modules this component * replaces</dd> * <dt>after:</dt> <dd>array of modules the components which, if * present, should be sorted above this one</dd> * <dt>after_map:</dt> <dd>faster alternative to 'after' -- supply * a hash instead of an array</dd> * <dt>rollup:</dt> <dd>the number of superseded modules required * for automatic rollup</dd> * <dt>fullpath:</dt> <dd>If fullpath is specified, this is used * instead of the configured base + path</dd> * <dt>skinnable:</dt> <dd>flag to determine if skin assets should * automatically be pulled in</dd> * <dt>submodules:</dt> <dd>a hash of submodules</dd> * <dt>group:</dt> <dd>The group the module belongs to -- this * is set automatically when it is added as part of a group * configuration.</dd> * <dt>lang:</dt> * <dd>array of BCP 47 language tags of languages for which this * module has localized resource bundles, * e.g., ["en-GB","zh-Hans-CN"]</dd> * <dt>condition:</dt> * <dd>Specifies that the module should be loaded automatically if * a condition is met. This is an object with up to three fields: * [trigger] - the name of a module that can trigger the auto-load * [test] - a function that returns true when the module is to be * loaded. * [when] - specifies the load order of the conditional module * with regard to the position of the trigger module. * This should be one of three values: 'before', 'after', or * 'instead'. The default is 'after'. * </dd> * <dt>testresults:</dt><dd>a hash of test results from Y.Features.all()</dd> * </dl> * @method addModule * @param {object} o An object containing the module data. * @param {string} name the module name (optional), required if not * in the module data. * @return {object} the module definition or null if * the object passed in did not provide all required attributes. */ addModule: function(o, name) { name = name || o.name; if (this.moduleInfo[name]) { //This catches temp modules loaded via a pattern // The module will be added twice, once from the pattern and // Once from the actual add call, this ensures that properties // that were added to the module the first time around (group: gallery) // are also added the second time around too. o = Y.merge(this.moduleInfo[name], o); } o.name = name; if (!o || !o.name) { return null; } if (!o.type) { o.type = JS; } if (!o.path && !o.fullpath) { o.path = _path(name, name, o.type); } o.supersedes = o.supersedes || o.use; o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true; o.requires = this.filterRequires(o.requires) || []; // Handle submodule logic var subs = o.submodules, i, l, sup, s, smod, plugins, plug, j, langs, packName, supName, flatSup, flatLang, lang, ret, overrides, skinname, when, conditions = this.conditions, trigger; // , existing = this.moduleInfo[name], newr; this.moduleInfo[name] = o; if (!o.langPack && o.lang) { langs = YArray(o.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } } } if (subs) { sup = o.supersedes || []; l = 0; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; s.path = s.path || _path(name, i, o.type); s.pkg = name; s.group = o.group; if (s.supersedes) { sup = sup.concat(s.supersedes); } smod = this.addModule(s, i); sup.push(i); if (smod.skinnable) { o.skinnable = true; overrides = this.skin.overrides; if (overrides && overrides[i]) { for (j = 0; j < overrides[i].length; j++) { skinname = this._addSkin(overrides[i][j], i, name); sup.push(skinname); } } skinname = this._addSkin(this.skin.defaultSkin, i, name); sup.push(skinname); } // looks like we are expected to work out the metadata // for the parent module language packs from what is // specified in the child modules. if (s.lang && s.lang.length) { langs = YArray(s.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); supName = this.getLangPackName(lang, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } flatSup = flatSup || YArray.hash(smod.supersedes); if (!(supName in flatSup)) { smod.supersedes.push(supName); } o.lang = o.lang || []; flatLang = flatLang || YArray.hash(o.lang); if (!(lang in flatLang)) { o.lang.push(lang); } // Add rollup file, need to add to supersedes list too // default packages packName = this.getLangPackName(ROOT_LANG, name); supName = this.getLangPackName(ROOT_LANG, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } if (!(supName in flatSup)) { smod.supersedes.push(supName); } // Add rollup file, need to add to supersedes list too } } l++; } } //o.supersedes = YObject.keys(YArray.hash(sup)); o.supersedes = YArray.dedupe(sup); if (this.allowRollup) { o.rollup = (l < 4) ? l : Math.min(l - 1, 4); } } plugins = o.plugins; if (plugins) { for (i in plugins) { if (plugins.hasOwnProperty(i)) { plug = plugins[i]; plug.pkg = name; plug.path = plug.path || _path(name, i, o.type); plug.requires = plug.requires || []; plug.group = o.group; this.addModule(plug, i); if (o.skinnable) { this._addSkin(this.skin.defaultSkin, i, name); } } } } if (o.condition) { trigger = o.condition.trigger; when = o.condition.when; conditions[trigger] = conditions[trigger] || {}; conditions[trigger][name] = o.condition; // the 'when' attribute can be 'before', 'after', or 'instead' // the default is after. if (when && when != 'after') { if (when == 'instead') { // replace the trigger o.supersedes = o.supersedes || []; o.supersedes.push(trigger); } else { // before the trigger // the trigger requires the conditional mod, // so it should appear before the conditional // mod if we do not intersede. } } else { // after the trigger o.after = o.after || []; o.after.push(trigger); } } if (o.after) { o.after_map = YArray.hash(o.after); } // this.dirty = true; if (o.configFn) { ret = o.configFn(o); if (ret === false) { delete this.moduleInfo[name]; o = null; } } return o; }, /** * Add a requirement for one or more module * @method require * @param {string[] | string*} what the modules to load. */ require: function(what) { var a = (typeof what === 'string') ? YArray(arguments) : what; this.dirty = true; this.required = Y.merge(this.required, YArray.hash(this.filterRequires(a))); this._explodeRollups(); }, /** * Grab all the items that were asked for, check to see if the Loader * meta-data contains a "use" array. If it doesm remove the asked item and replace it with * the content of the "use". * This will make asking for: "dd" * Actually ask for: "dd-ddm-base,dd-ddm,dd-ddm-drop,dd-drag,dd-proxy,dd-constrain,dd-drop,dd-scroll,dd-drop-plugin" * @private * @method _explodeRollups */ _explodeRollups: function() { var self = this, m, r = self.required; if (!self.allowRollup) { oeach(r, function(v, name) { m = self.getModule(name); if (m && m.use) { //delete r[name]; YArray.each(m.use, function(v) { m = self.getModule(v); if (m && m.use) { //delete r[v]; YArray.each(m.use, function(v) { r[v] = true; }); } else { r[v] = true; } }); } }); self.required = r; } }, filterRequires: function(r) { if (r) { if (!Y.Lang.isArray(r)) { r = [r]; } r = Y.Array(r); var c = []; for (var i = 0; i < r.length; i++) { var mod = this.getModule(r[i]); if (mod && mod.use) { for (var o = 0; o < mod.use.length; o++) { c.push(mod.use[o]); } } else { c.push(r[i]); } } r = c; } return r; }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param {object} mod The module definition from moduleInfo. * @return {array} the expanded requirement list. */ getRequires: function(mod) { if (!mod || mod._parsed) { return NO_REQUIREMENTS; } var i, m, j, add, packName, lang, testresults = this.testresults, name = mod.name, cond, go, adddef = ON_PAGE[name] && ON_PAGE[name].details, d, k, m1, r, old_mod, o, skinmod, skindef, intl = mod.lang || mod.intl, info = this.moduleInfo, ftests = Y.Features && Y.Features.tests.load, hash; // console.log(name); // pattern match leaves module stub that needs to be filled out if (mod.temp && adddef) { old_mod = mod; mod = this.addModule(adddef, name); mod.group = old_mod.group; mod.pkg = old_mod.pkg; delete mod.expanded; } // console.log('cache: ' + mod.langCache + ' == ' + this.lang); // if (mod.expanded && (!mod.langCache || mod.langCache == this.lang)) { if (mod.expanded && (!this.lang || mod.langCache === this.lang)) { return mod.expanded; } d = []; hash = {}; r = this.filterRequires(mod.requires); if (mod.lang) { //If a module has a lang attribute, auto add the intl requirement. d.unshift('intl'); r.unshift('intl'); intl = true; } o = mod.optional; mod._parsed = true; mod.langCache = this.lang; for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { d.push(r[i]); hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } // get the requirements from superseded modules, if any r = mod.supersedes; if (r) { for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { // if this module has submodules, the requirements list is // expanded to include the submodules. This is so we can // prevent dups when a submodule is already loaded and the // parent is requested. if (mod.submodules) { d.push(r[i]); } hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } if (o && this.loadOptional) { for (i = 0; i < o.length; i++) { if (!hash[o[i]]) { d.push(o[i]); hash[o[i]] = true; m = info[o[i]]; if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } cond = this.conditions[name]; if (cond) { if (testresults && ftests) { oeach(testresults, function(result, id) { var condmod = ftests[id].name; if (!hash[condmod] && ftests[id].trigger == name) { if (result && ftests[id]) { hash[condmod] = true; d.push(condmod); } } }); } else { oeach(cond, function(def, condmod) { if (!hash[condmod]) { go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y, r))); if (go) { hash[condmod] = true; d.push(condmod); m = this.getModule(condmod); if (m) { add = this.getRequires(m); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } }, this); } } // Create skin modules if (mod.skinnable) { skindef = this.skin.overrides; if (skindef && skindef[name]) { for (i = 0; i < skindef[name].length; i++) { skinmod = this._addSkin(skindef[name][i], name); d.push(skinmod); } } else { skinmod = this._addSkin(this.skin.defaultSkin, name); d.push(skinmod); } } mod._parsed = false; if (intl) { if (mod.lang && !mod.langPack && Y.Intl) { lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang); packName = this.getLangPackName(lang, name); if (packName) { d.unshift(packName); } } d.unshift(INTL); } mod.expanded_map = YArray.hash(d); mod.expanded = YObject.keys(mod.expanded_map); return mod.expanded; }, /** * Returns a hash of module names the supplied module satisfies. * @method getProvides * @param {string} name The name of the module. * @return {object} what this module provides. */ getProvides: function(name) { var m = this.getModule(name), o, s; // supmap = this.provides; if (!m) { return NOT_FOUND; } if (m && !m.provides) { o = {}; s = m.supersedes; if (s) { YArray.each(s, function(v) { Y.mix(o, this.getProvides(v)); }, this); } o[name] = true; m.provides = o; } return m.provides; }, /** * Calculates the dependency tree, the result is stored in the sorted * property. * @method calculate * @param {object} o optional options object. * @param {string} type optional argument to prune modules. */ calculate: function(o, type) { if (o || type || this.dirty) { if (o) { this._config(o); } if (!this._init) { this._setup(); } this._explode(); if (this.allowRollup) { this._rollup(); } else { this._explodeRollups(); } this._reduce(); this._sort(); } }, _addLangPack: function(lang, m, packName) { var name = m.name, packPath, existing = this.moduleInfo[packName]; if (!existing) { packPath = _path((m.pkg || name), packName, JS, true); this.addModule({ path: packPath, intl: true, langPack: true, ext: m.ext, group: m.group, supersedes: [] }, packName); if (lang) { Y.Env.lang = Y.Env.lang || {}; Y.Env.lang[lang] = Y.Env.lang[lang] || {}; Y.Env.lang[lang][name] = true; } } return this.moduleInfo[packName]; }, /** * Investigates the current YUI configuration on the page. By default, * modules already detected will not be loaded again unless a force * option is encountered. Called by calculate() * @method _setup * @private */ _setup: function() { var info = this.moduleInfo, name, i, j, m, l, packName; for (name in info) { if (info.hasOwnProperty(name)) { m = info[name]; if (m) { // remove dups //m.requires = YObject.keys(YArray.hash(m.requires)); m.requires = YArray.dedupe(m.requires); // Create lang pack modules if (m.lang && m.lang.length) { // Setup root package if the module has lang defined, // it needs to provide a root language pack packName = this.getLangPackName(ROOT_LANG, name); this._addLangPack(null, m, packName); } } } } //l = Y.merge(this.inserted); l = {}; // available modules if (!this.ignoreRegistered) { Y.mix(l, GLOBAL_ENV.mods); } // add the ignore list to the list of loaded packages if (this.ignore) { Y.mix(l, YArray.hash(this.ignore)); } // expand the list to include superseded modules for (j in l) { if (l.hasOwnProperty(j)) { Y.mix(l, this.getProvides(j)); } } // remove modules on the force list from the loaded list if (this.force) { for (i = 0; i < this.force.length; i++) { if (this.force[i] in l) { delete l[this.force[i]]; } } } Y.mix(this.loaded, l); this._init = true; }, /** * Builds a module name for a language pack * @method getLangPackName * @param {string} lang the language code. * @param {string} mname the module to build it for. * @return {string} the language pack module name. */ getLangPackName: function(lang, mname) { return ('lang/' + mname + ((lang) ? '_' + lang : '')); }, /** * Inspects the required modules list looking for additional * dependencies. Expands the required list to include all * required modules. Called by calculate() * @method _explode * @private */ _explode: function() { var r = this.required, m, reqs, done = {}, self = this; // the setup phase is over, all modules have been created self.dirty = false; self._explodeRollups(); r = self.required; oeach(r, function(v, name) { if (!done[name]) { done[name] = true; m = self.getModule(name); if (m) { var expound = m.expound; if (expound) { r[expound] = self.getModule(expound); reqs = self.getRequires(r[expound]); Y.mix(r, YArray.hash(reqs)); } reqs = self.getRequires(m); Y.mix(r, YArray.hash(reqs)); } } }); }, getModule: function(mname) { //TODO: Remove name check - it's a quick hack to fix pattern WIP if (!mname) { return null; } var p, found, pname, m = this.moduleInfo[mname], patterns = this.patterns; // check the patterns library to see if we should automatically add // the module with defaults if (!m) { for (pname in patterns) { if (patterns.hasOwnProperty(pname)) { p = patterns[pname]; // use the metadata supplied for the pattern // as the module definition. if (mname.indexOf(pname) > -1) { found = p; break; } } } if (found) { if (p.action) { p.action.call(this, mname, pname); } else { // ext true or false? m = this.addModule(Y.merge(found), mname); m.temp = true; } } } return m; }, // impl in rollup submodule _rollup: function() { }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @return {object} the reduced dependency hash. * @private */ _reduce: function(r) { r = r || this.required; var i, j, s, m, type = this.loadType; for (i in r) { if (r.hasOwnProperty(i)) { m = this.getModule(i); // remove if already loaded if (((this.loaded[i] || ON_PAGE[i]) && !this.forceMap[i] && !this.ignoreRegistered) || (type && m && m.type != type)) { delete r[i]; } // remove anything this module supersedes s = m && m.supersedes; if (s) { for (j = 0; j < s.length; j++) { if (s[j] in r) { delete r[s[j]]; } } } } } return r; }, _finish: function(msg, success) { _queue.running = false; var onEnd = this.onEnd; if (onEnd) { onEnd.call(this.context, { msg: msg, data: this.data, success: success }); } this._continue(); }, _onSuccess: function() { var self = this, skipped = Y.merge(self.skipped), fn, failed = [], rreg = self.requireRegistration, success, msg; oeach(skipped, function(k) { delete self.inserted[k]; }); self.skipped = {}; oeach(self.inserted, function(v, k) { var mod = self.getModule(k); if (mod && rreg && mod.type == JS && !(k in YUI.Env.mods)) { failed.push(k); } else { Y.mix(self.loaded, self.getProvides(k)); } }); fn = self.onSuccess; msg = (failed.length) ? 'notregistered' : 'success'; success = !(failed.length); if (fn) { fn.call(self.context, { msg: msg, data: self.data, success: success, failed: failed, skipped: skipped }); } self._finish(msg, success); }, _onFailure: function(o) { var f = this.onFailure, msg = 'failure: ' + o.msg; if (f) { f.call(this.context, { msg: msg, data: this.data, success: false }); } this._finish(msg, false); }, _onTimeout: function() { var f = this.onTimeout; if (f) { f.call(this.context, { msg: 'timeout', data: this.data, success: false }); } this._finish('timeout', false); }, /** * Sorts the dependency tree. The last step of calculate() * @method _sort * @private */ _sort: function() { // create an indexed list var s = YObject.keys(this.required), // loaded = this.loaded, done = {}, p = 0, l, a, b, j, k, moved, doneKey; // keep going until we make a pass without moving anything for (;;) { l = s.length; moved = false; // start the loop after items that are already sorted for (j = p; j < l; j++) { // check the next module on the list to see if its // dependencies have been met a = s[j]; // check everything below current item and move if we // find a requirement for the current item for (k = j + 1; k < l; k++) { doneKey = a + s[k]; if (!done[doneKey] && this._requires(a, s[k])) { // extract the dependency so we can move it up b = s.splice(k, 1); // insert the dependency above the item that // requires it s.splice(j, 0, b[0]); // only swap two dependencies once to short circut // circular dependencies done[doneKey] = true; // keep working moved = true; break; } } // jump out of loop if we moved something if (moved) { break; // this item is sorted, move our pointer and keep going } else { p++; } } // when we make it here and moved is false, we are // finished sorting if (!moved) { break; } } this.sorted = s; }, partial: function(partial, o, type) { this.sorted = partial; this.insert(o, type, true); }, _insert: function(source, o, type, skipcalc) { // restore the state at the time of the request if (source) { this._config(source); } // build the dependency list // don't include type so we can process CSS and script in // one pass when the type is not specified. if (!skipcalc) { this.calculate(o); } this.loadType = type; if (!type) { var self = this; this._internalCallback = function() { var f = self.onCSS, n, p, sib; // IE hack for style overrides that are not being applied if (this.insertBefore && Y.UA.ie) { n = Y.config.doc.getElementById(this.insertBefore); p = n.parentNode; sib = n.nextSibling; p.removeChild(n); if (sib) { p.insertBefore(n, sib); } else { p.appendChild(n); } } if (f) { f.call(self.context, Y); } self._internalCallback = null; self._insert(null, null, JS); }; this._insert(null, null, CSS); return; } // set a flag to indicate the load has started this._loading = true; // flag to indicate we are done with the combo service // and any additional files will need to be loaded // individually this._combineComplete = {}; // start the load this.loadNext(); }, // Once a loader operation is completely finished, process // any additional queued items. _continue: function() { if (!(_queue.running) && _queue.size() > 0) { _queue.running = true; _queue.next()(); } }, /** * inserts the requested modules and their dependencies. * <code>type</code> can be "js" or "css". Both script and * css are inserted if type is not provided. * @method insert * @param {object} o optional options object. * @param {string} type the type of dependency to insert. */ insert: function(o, type, skipsort) { var self = this, copy = Y.merge(this); delete copy.require; delete copy.dirty; _queue.add(function() { self._insert(copy, o, type, skipsort); }); this._continue(); }, /** * Executed every time a module is loaded, and if we are in a load * cycle, we attempt to load the next script. Public so that it * is possible to call this if using a method other than * Y.register to determine when scripts are fully loaded * @method loadNext * @param {string} mname optional the name of the module that has * been loaded (which is usually why it is time to load the next * one). */ loadNext: function(mname) { // It is possible that this function is executed due to something // else one the page loading a YUI module. Only react when we // are actively loading something if (!this._loading) { return; } var s, len, i, m, url, fn, msg, attr, group, groupName, j, frag, comboSource, comboSources, mods, combining, urls, comboBase, self = this, type = self.loadType, handleSuccess = function(o) { self.loadNext(o.data); }, handleCombo = function(o) { self._combineComplete[type] = true; var i, len = combining.length; for (i = 0; i < len; i++) { self.inserted[combining[i]] = true; } handleSuccess(o); }; if (self.combine && (!self._combineComplete[type])) { combining = []; self._combining = combining; s = self.sorted; len = s.length; // the default combo base comboBase = self.comboBase; url = comboBase; urls = []; comboSources = {}; for (i = 0; i < len; i++) { comboSource = comboBase; m = self.getModule(s[i]); groupName = m && m.group; if (groupName) { group = self.groups[groupName]; if (!group.combine) { m.combine = false; continue; } m.combine = true; if (group.comboBase) { comboSource = group.comboBase; } if ("root" in group && L.isValue(group.root)) { m.root = group.root; } } comboSources[comboSource] = comboSources[comboSource] || []; comboSources[comboSource].push(m); } for (j in comboSources) { if (comboSources.hasOwnProperty(j)) { url = j; mods = comboSources[j]; len = mods.length; for (i = 0; i < len; i++) { // m = self.getModule(s[i]); m = mods[i]; // Do not try to combine non-yui JS unless combo def // is found if (m && (m.type === type) && (m.combine || !m.ext)) { frag = ((L.isValue(m.root)) ? m.root : self.root) + m.path; if ((url !== j) && (i < (len - 1)) && ((frag.length + url.length) > self.maxURLLength)) { urls.push(self._filter(url)); url = j; } url += frag; if (i < (len - 1)) { url += '&'; } combining.push(m.name); } } if (combining.length && (url != j)) { urls.push(self._filter(url)); } } } if (combining.length) { // if (m.type === CSS) { if (type === CSS) { fn = Y.Get.css; attr = self.cssAttributes; } else { fn = Y.Get.script; attr = self.jsAttributes; } fn(urls, { data: self._loading, onSuccess: handleCombo, onFailure: self._onFailure, onTimeout: self._onTimeout, insertBefore: self.insertBefore, charset: self.charset, attributes: attr, timeout: self.timeout, autopurge: false, context: self }); return; } else { self._combineComplete[type] = true; } } if (mname) { // if the module that was just loaded isn't what we were expecting, // continue to wait if (mname !== self._loading) { return; } // The global handler that is called when each module is loaded // will pass that module name to this function. Storing this // data to avoid loading the same module multiple times // centralize this in the callback self.inserted[mname] = true; // self.loaded[mname] = true; // provided = self.getProvides(mname); // Y.mix(self.loaded, provided); // Y.mix(self.inserted, provided); if (self.onProgress) { self.onProgress.call(self.context, { name: mname, data: self.data }); } } s = self.sorted; len = s.length; for (i = 0; i < len; i = i + 1) { // this.inserted keeps track of what the loader has loaded. // move on if this item is done. if (s[i] in self.inserted) { continue; } // Because rollups will cause multiple load notifications // from Y, loadNext may be called multiple times for // the same module when loading a rollup. We can safely // skip the subsequent requests if (s[i] === self._loading) { return; } // log("inserting " + s[i]); m = self.getModule(s[i]); if (!m) { if (!self.skipped[s[i]]) { msg = 'Undefined module ' + s[i] + ' skipped'; // self.inserted[s[i]] = true; self.skipped[s[i]] = true; } continue; } group = (m.group && self.groups[m.group]) || NOT_FOUND; // The load type is stored to offer the possibility to load // the css separately from the script. if (!type || type === m.type) { self._loading = s[i]; if (m.type === CSS) { fn = Y.Get.css; attr = self.cssAttributes; } else { fn = Y.Get.script; attr = self.jsAttributes; } url = (m.fullpath) ? self._filter(m.fullpath, s[i]) : self._url(m.path, s[i], group.base || m.base); fn(url, { data: s[i], onSuccess: handleSuccess, insertBefore: self.insertBefore, charset: self.charset, attributes: attr, onFailure: self._onFailure, onTimeout: self._onTimeout, timeout: self.timeout, autopurge: false, context: self }); return; } } // we are finished self._loading = null; fn = self._internalCallback; // internal callback for loading css first if (fn) { self._internalCallback = null; fn.call(self); } else { self._onSuccess(); } }, /** * Apply filter defined for this instance to a url/path * method _filter * @param {string} u the string to filter. * @param {string} name the name of the module, if we are processing * a single module as opposed to a combined url. * @return {string} the filtered string. * @private */ _filter: function(u, name) { var f = this.filter, hasFilter = name && (name in this.filters), modFilter = hasFilter && this.filters[name]; if (u) { if (hasFilter) { f = (L.isString(modFilter)) ? this.FILTER_DEFS[modFilter.toUpperCase()] || null : modFilter; } if (f) { u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr); } } return u; }, /** * Generates the full url for a module * method _url * @param {string} path the path fragment. * @return {string} the full url. * @private */ _url: function(path, name, base) { return this._filter((base || this.base || '') + path, name); } }; }, '@VERSION@' ,{requires:['get']}); YUI.add('loader-rollup', function(Y) { /** * Optional automatic rollup logic for reducing http connections * when not using a combo service. * @module loader * @submodule rollup */ /** * Look for rollup packages to determine if all of the modules a * rollup supersedes are required. If so, include the rollup to * help reduce the total number of connections required. Called * by calculate(). This is an optional feature, and requires the * appropriate submodule to function. * @method _rollup * @for Loader * @private */ Y.Loader.prototype._rollup = function() { var i, j, m, s, r = this.required, roll, info = this.moduleInfo, rolled, c, smod; // find and cache rollup modules if (this.dirty || !this.rollups) { this.rollups = {}; for (i in info) { if (info.hasOwnProperty(i)) { m = this.getModule(i); // if (m && m.rollup && m.supersedes) { if (m && m.rollup) { this.rollups[i] = m; } } } this.forceMap = (this.force) ? Y.Array.hash(this.force) : {}; } // make as many passes as needed to pick up rollup rollups for (;;) { rolled = false; // go through the rollup candidates for (i in this.rollups) { if (this.rollups.hasOwnProperty(i)) { // there can be only one, unless forced if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) { m = this.getModule(i); s = m.supersedes || []; roll = false; // @TODO remove continue if (!m.rollup) { continue; } c = 0; // check the threshold for (j = 0; j < s.length; j++) { smod = info[s[j]]; // if the superseded module is loaded, we can't // load the rollup unless it has been forced. if (this.loaded[s[j]] && !this.forceMap[s[j]]) { roll = false; break; // increment the counter if this module is required. // if we are beyond the rollup threshold, we will // use the rollup module } else if (r[s[j]] && m.type == smod.type) { c++; roll = (c >= m.rollup); if (roll) { break; } } } if (roll) { // add the rollup r[i] = true; rolled = true; // expand the rollup's dependencies this.getRequires(m); } } } } // if we made it here w/o rolling up something, we are done if (!rolled) { break; } } }; }, '@VERSION@' ,{requires:['loader-base']}); YUI.add('loader-yui3', function(Y) { /* This file is auto-generated by src/loader/meta_join.py */ /** * YUI 3 module metadata * @module loader * @submodule yui3 */ YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || { "align-plugin": { "requires": [ "node-screen", "node-pluginhost" ] }, "anim": { "use": [ "anim-base", "anim-color", "anim-curve", "anim-easing", "anim-node-plugin", "anim-scroll", "anim-xy" ] }, "anim-base": { "requires": [ "base-base", "node-style" ] }, "anim-color": { "requires": [ "anim-base" ] }, "anim-curve": { "requires": [ "anim-xy" ] }, "anim-easing": { "requires": [ "anim-base" ] }, "anim-node-plugin": { "requires": [ "node-pluginhost", "anim-base" ] }, "anim-scroll": { "requires": [ "anim-base" ] }, "anim-xy": { "requires": [ "anim-base", "node-screen" ] }, "app": { "use": [ "controller", "model", "model-list", "view" ] }, "array-extras": {}, "array-invoke": {}, "arraylist": {}, "arraylist-add": { "requires": [ "arraylist" ] }, "arraylist-filter": { "requires": [ "arraylist" ] }, "arraysort": { "requires": [ "yui-base" ] }, "async-queue": { "requires": [ "event-custom" ] }, "attribute": { "use": [ "attribute-base", "attribute-complex" ] }, "attribute-base": { "requires": [ "event-custom" ] }, "attribute-complex": { "requires": [ "attribute-base" ] }, "autocomplete": { "use": [ "autocomplete-base", "autocomplete-sources", "autocomplete-list", "autocomplete-plugin" ] }, "autocomplete-base": { "optional": [ "autocomplete-sources" ], "requires": [ "array-extras", "base-build", "escape", "event-valuechange", "node-base" ] }, "autocomplete-filters": { "requires": [ "array-extras", "text-wordbreak" ] }, "autocomplete-filters-accentfold": { "requires": [ "array-extras", "text-accentfold", "text-wordbreak" ] }, "autocomplete-highlighters": { "requires": [ "array-extras", "highlight-base" ] }, "autocomplete-highlighters-accentfold": { "requires": [ "array-extras", "highlight-accentfold" ] }, "autocomplete-list": { "after": [ "autocomplete-sources" ], "lang": [ "en" ], "requires": [ "autocomplete-base", "event-resize", "selector-css3", "shim-plugin", "widget", "widget-position", "widget-position-align" ], "skinnable": true }, "autocomplete-list-keys": { "condition": { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }, "requires": [ "autocomplete-list", "base-build" ] }, "autocomplete-plugin": { "requires": [ "autocomplete-list", "node-pluginhost" ] }, "autocomplete-sources": { "optional": [ "io-base", "json-parse", "jsonp", "yql" ], "requires": [ "autocomplete-base" ] }, "base": { "use": [ "base-base", "base-pluginhost", "base-build" ] }, "base-base": { "after": [ "attribute-complex" ], "requires": [ "attribute-base" ] }, "base-build": { "requires": [ "base-base" ] }, "base-pluginhost": { "requires": [ "base-base", "pluginhost" ] }, "cache": { "use": [ "cache-base", "cache-offline", "cache-plugin" ] }, "cache-base": { "requires": [ "base" ] }, "cache-offline": { "requires": [ "cache-base", "json" ] }, "cache-plugin": { "requires": [ "plugin", "cache-base" ] }, "calendar": { "lang": [ "en", "ru" ], "requires": [ "calendar-base" ], "skinnable": true }, "calendar-base": { "lang": [ "en", "ru" ], "requires": [ "widget", "substitute", "datatype-date", "datatype-date-math" ], "skinnable": true }, "charts": { "requires": [ "dom", "datatype", "event-custom", "event-mouseenter", "widget", "widget-position", "widget-stack", "graphics" ] }, "classnamemanager": { "requires": [ "yui-base" ] }, "clickable-rail": { "requires": [ "slider-base" ] }, "collection": { "use": [ "array-extras", "arraylist", "arraylist-add", "arraylist-filter", "array-invoke" ] }, "compat": { "requires": [ "event-base", "dom", "dump", "substitute" ] }, "console": { "lang": [ "en", "es" ], "requires": [ "yui-log", "widget", "substitute" ], "skinnable": true }, "console-filters": { "requires": [ "plugin", "console" ], "skinnable": true }, "controller": { "optional": [ "querystring-parse" ], "requires": [ "array-extras", "base-build", "history" ] }, "cookie": { "requires": [ "yui-base" ] }, "createlink-base": { "requires": [ "editor-base" ] }, "cssbase": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssbase-context": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssfonts": { "type": "css" }, "cssfonts-context": { "type": "css" }, "cssgrids": { "optional": [ "cssreset", "cssfonts" ], "type": "css" }, "cssgrids-context-deprecated": { "optional": [ "cssreset-context" ], "requires": [ "cssfonts-context" ], "type": "css" }, "cssgrids-deprecated": { "optional": [ "cssreset" ], "requires": [ "cssfonts" ], "type": "css" }, "cssreset": { "type": "css" }, "cssreset-context": { "type": "css" }, "dataschema": { "use": [ "dataschema-base", "dataschema-json", "dataschema-xml", "dataschema-array", "dataschema-text" ] }, "dataschema-array": { "requires": [ "dataschema-base" ] }, "dataschema-base": { "requires": [ "base" ] }, "dataschema-json": { "requires": [ "dataschema-base", "json" ] }, "dataschema-text": { "requires": [ "dataschema-base" ] }, "dataschema-xml": { "requires": [ "dataschema-base" ] }, "datasource": { "use": [ "datasource-local", "datasource-io", "datasource-get", "datasource-function", "datasource-cache", "datasource-jsonschema", "datasource-xmlschema", "datasource-arrayschema", "datasource-textschema", "datasource-polling" ] }, "datasource-arrayschema": { "requires": [ "datasource-local", "plugin", "dataschema-array" ] }, "datasource-cache": { "requires": [ "datasource-local", "plugin", "cache-base" ] }, "datasource-function": { "requires": [ "datasource-local" ] }, "datasource-get": { "requires": [ "datasource-local", "get" ] }, "datasource-io": { "requires": [ "datasource-local", "io-base" ] }, "datasource-jsonschema": { "requires": [ "datasource-local", "plugin", "dataschema-json" ] }, "datasource-local": { "requires": [ "base" ] }, "datasource-polling": { "requires": [ "datasource-local" ] }, "datasource-textschema": { "requires": [ "datasource-local", "plugin", "dataschema-text" ] }, "datasource-xmlschema": { "requires": [ "datasource-local", "plugin", "dataschema-xml" ] }, "datatable": { "use": [ "datatable-base", "datatable-datasource", "datatable-sort", "datatable-scroll" ] }, "datatable-base": { "requires": [ "recordset-base", "widget", "substitute", "event-mouseenter" ], "skinnable": true }, "datatable-datasource": { "requires": [ "datatable-base", "plugin", "datasource-local" ] }, "datatable-scroll": { "requires": [ "datatable-base", "plugin", "stylesheet" ] }, "datatable-sort": { "lang": [ "en" ], "requires": [ "datatable-base", "plugin", "recordset-sort" ] }, "datatype": { "use": [ "datatype-number", "datatype-date", "datatype-xml" ] }, "datatype-date": { "supersedes": [ "datatype-date-format" ], "use": [ "datatype-date-parse", "datatype-date-format" ] }, "datatype-date-format": { "lang": [ "ar", "ar-JO", "ca", "ca-ES", "da", "da-DK", "de", "de-AT", "de-DE", "el", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", "en-JO", "en-MY", "en-NZ", "en-PH", "en-SG", "en-US", "es", "es-AR", "es-BO", "es-CL", "es-CO", "es-EC", "es-ES", "es-MX", "es-PE", "es-PY", "es-US", "es-UY", "es-VE", "fi", "fi-FI", "fr", "fr-BE", "fr-CA", "fr-FR", "hi", "hi-IN", "id", "id-ID", "it", "it-IT", "ja", "ja-JP", "ko", "ko-KR", "ms", "ms-MY", "nb", "nb-NO", "nl", "nl-BE", "nl-NL", "pl", "pl-PL", "pt", "pt-BR", "ro", "ro-RO", "ru", "ru-RU", "sv", "sv-SE", "th", "th-TH", "tr", "tr-TR", "vi", "vi-VN", "zh-Hans", "zh-Hans-CN", "zh-Hant", "zh-Hant-HK", "zh-Hant-TW" ] }, "datatype-date-math": { "requires": [ "yui-base" ] }, "datatype-date-parse": {}, "datatype-number": { "use": [ "datatype-number-parse", "datatype-number-format" ] }, "datatype-number-format": {}, "datatype-number-parse": {}, "datatype-xml": { "use": [ "datatype-xml-parse", "datatype-xml-format" ] }, "datatype-xml-format": {}, "datatype-xml-parse": {}, "dd": { "use": [ "dd-ddm-base", "dd-ddm", "dd-ddm-drop", "dd-drag", "dd-proxy", "dd-constrain", "dd-drop", "dd-scroll", "dd-delegate" ] }, "dd-constrain": { "requires": [ "dd-drag" ] }, "dd-ddm": { "requires": [ "dd-ddm-base", "event-resize" ] }, "dd-ddm-base": { "requires": [ "node", "base", "yui-throttle", "classnamemanager" ] }, "dd-ddm-drop": { "requires": [ "dd-ddm" ] }, "dd-delegate": { "requires": [ "dd-drag", "dd-drop-plugin", "event-mouseenter" ] }, "dd-drag": { "requires": [ "dd-ddm-base" ] }, "dd-drop": { "requires": [ "dd-drag", "dd-ddm-drop" ] }, "dd-drop-plugin": { "requires": [ "dd-drop" ] }, "dd-gestures": { "condition": { "name": "dd-gestures", "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }, "requires": [ "dd-drag", "event-synthetic", "event-gestures" ] }, "dd-plugin": { "optional": [ "dd-constrain", "dd-proxy" ], "requires": [ "dd-drag" ] }, "dd-proxy": { "requires": [ "dd-drag" ] }, "dd-scroll": { "requires": [ "dd-drag" ] }, "dial": { "lang": [ "en", "es" ], "requires": [ "widget", "dd-drag", "substitute", "event-mouseenter", "event-move", "event-key", "transition", "intl" ], "skinnable": true }, "dom": { "use": [ "dom-base", "dom-screen", "dom-style", "selector-native", "selector" ] }, "dom-base": { "requires": [ "dom-core" ] }, "dom-core": { "requires": [ "oop", "features" ] }, "dom-deprecated": { "requires": [ "dom-base" ] }, "dom-screen": { "requires": [ "dom-base", "dom-style" ] }, "dom-style": { "requires": [ "dom-base" ] }, "dom-style-ie": { "condition": { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }, "requires": [ "dom-style" ] }, "dump": {}, "editor": { "use": [ "frame", "selection", "exec-command", "editor-base", "editor-para", "editor-br", "editor-bidi", "editor-tab", "createlink-base" ] }, "editor-base": { "requires": [ "base", "frame", "node", "exec-command", "selection" ] }, "editor-bidi": { "requires": [ "editor-base" ] }, "editor-br": { "requires": [ "editor-base" ] }, "editor-lists": { "requires": [ "editor-base" ] }, "editor-para": { "requires": [ "editor-base" ] }, "editor-tab": { "requires": [ "editor-base" ] }, "escape": {}, "event": { "after": [ "node-base" ], "use": [ "event-base", "event-delegate", "event-synthetic", "event-mousewheel", "event-mouseenter", "event-key", "event-focus", "event-resize", "event-hover", "event-outside" ] }, "event-base": { "after": [ "node-base" ], "requires": [ "event-custom-base" ] }, "event-base-ie": { "after": [ "event-base" ], "condition": { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }, "requires": [ "node-base" ] }, "event-custom": { "use": [ "event-custom-base", "event-custom-complex" ] }, "event-custom-base": { "requires": [ "oop" ] }, "event-custom-complex": { "requires": [ "event-custom-base" ] }, "event-delegate": { "requires": [ "node-base" ] }, "event-flick": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-focus": { "requires": [ "event-synthetic" ] }, "event-gestures": { "use": [ "event-flick", "event-move" ] }, "event-hover": { "requires": [ "event-mouseenter" ] }, "event-key": { "requires": [ "event-synthetic" ] }, "event-mouseenter": { "requires": [ "event-synthetic" ] }, "event-mousewheel": { "requires": [ "node-base" ] }, "event-move": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-outside": { "requires": [ "event-synthetic" ] }, "event-resize": { "requires": [ "node-base" ] }, "event-simulate": { "requires": [ "event-base" ] }, "event-synthetic": { "requires": [ "node-base", "event-custom-complex" ] }, "event-touch": { "requires": [ "node-base" ] }, "event-valuechange": { "requires": [ "event-focus", "event-synthetic" ] }, "exec-command": { "requires": [ "frame" ] }, "features": { "requires": [ "yui-base" ] }, "frame": { "requires": [ "base", "node", "selector-css3", "substitute", "yui-throttle" ] }, "get": { "requires": [ "yui-base" ] }, "graphics": { "requires": [ "node", "event-custom", "pluginhost" ] }, "graphics-canvas": { "condition": { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT.createElement("canvas"); return (!DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" } }, "graphics-canvas-default": { "condition": { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT.createElement("canvas"); return (!DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" } }, "graphics-svg": { "condition": { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" } }, "graphics-svg-default": { "condition": { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" } }, "graphics-vml": { "condition": { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT.createElement("canvas"); return (!DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" } }, "graphics-vml-default": { "condition": { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT.createElement("canvas"); return (!DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" } }, "highlight": { "use": [ "highlight-base", "highlight-accentfold" ] }, "highlight-accentfold": { "requires": [ "highlight-base", "text-accentfold" ] }, "highlight-base": { "requires": [ "array-extras", "escape", "text-wordbreak" ] }, "history": { "use": [ "history-base", "history-hash", "history-hash-ie", "history-html5" ] }, "history-base": { "requires": [ "event-custom-complex" ] }, "history-hash": { "after": [ "history-html5" ], "requires": [ "event-synthetic", "history-base", "yui-later" ] }, "history-hash-ie": { "condition": { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }, "requires": [ "history-hash", "node-base" ] }, "history-html5": { "optional": [ "json" ], "requires": [ "event-base", "history-base", "node-base" ] }, "imageloader": { "requires": [ "base-base", "node-style", "node-screen" ] }, "intl": { "requires": [ "intl-base", "event-custom" ] }, "intl-base": { "requires": [ "yui-base" ] }, "io": { "use": [ "io-base", "io-xdr", "io-form", "io-upload-iframe", "io-queue" ] }, "io-base": { "requires": [ "event-custom-base", "querystring-stringify-simple" ] }, "io-form": { "requires": [ "io-base", "node-base" ] }, "io-queue": { "requires": [ "io-base", "queue-promote" ] }, "io-upload-iframe": { "requires": [ "io-base", "node-base" ] }, "io-xdr": { "requires": [ "io-base", "datatype-xml" ] }, "json": { "use": [ "json-parse", "json-stringify" ] }, "json-parse": {}, "json-stringify": {}, "jsonp": { "requires": [ "get", "oop" ] }, "jsonp-url": { "requires": [ "jsonp" ] }, "loader": { "use": [ "loader-base", "loader-rollup", "loader-yui3" ] }, "loader-base": { "requires": [ "get" ] }, "loader-rollup": { "requires": [ "loader-base" ] }, "loader-yui3": { "requires": [ "loader-base" ] }, "model": { "requires": [ "base-build", "escape", "json-parse" ] }, "model-list": { "requires": [ "array-extras", "array-invoke", "arraylist", "base-build", "json-parse", "model" ] }, "node": { "use": [ "node-base", "node-event-delegate", "node-pluginhost", "node-screen", "node-style" ] }, "node-base": { "requires": [ "event-base", "node-core", "dom-base" ] }, "node-core": { "requires": [ "dom-core", "selector" ] }, "node-deprecated": { "requires": [ "node-base" ] }, "node-event-delegate": { "requires": [ "node-base", "event-delegate" ] }, "node-event-html5": { "requires": [ "node-base" ] }, "node-event-simulate": { "requires": [ "node-base", "event-simulate" ] }, "node-flick": { "requires": [ "classnamemanager", "transition", "event-flick", "plugin" ], "skinnable": true }, "node-focusmanager": { "requires": [ "attribute", "node", "plugin", "node-event-simulate", "event-key", "event-focus" ] }, "node-load": { "requires": [ "node-base", "io-base" ] }, "node-menunav": { "requires": [ "node", "classnamemanager", "plugin", "node-focusmanager" ], "skinnable": true }, "node-pluginhost": { "requires": [ "node-base", "pluginhost" ] }, "node-screen": { "requires": [ "dom-screen", "node-base" ] }, "node-style": { "requires": [ "dom-style", "node-base" ] }, "oop": { "requires": [ "yui-base" ] }, "overlay": { "requires": [ "widget", "widget-stdmod", "widget-position", "widget-position-align", "widget-stack", "widget-position-constrain" ], "skinnable": true }, "plugin": { "requires": [ "base-base" ] }, "pluginattr": { "requires": [ "plugin" ] }, "pluginhost": { "use": [ "pluginhost-base", "pluginhost-config" ] }, "pluginhost-base": { "requires": [ "yui-base" ] }, "pluginhost-config": { "requires": [ "pluginhost-base" ] }, "profiler": { "requires": [ "yui-base" ] }, "querystring": { "use": [ "querystring-parse", "querystring-stringify" ] }, "querystring-parse": { "requires": [ "yui-base", "array-extras" ] }, "querystring-parse-simple": { "requires": [ "yui-base" ] }, "querystring-stringify": { "requires": [ "yui-base" ] }, "querystring-stringify-simple": { "requires": [ "yui-base" ] }, "queue-promote": { "requires": [ "yui-base" ] }, "range-slider": { "requires": [ "slider-base", "slider-value-range", "clickable-rail" ] }, "recordset": { "use": [ "recordset-base", "recordset-sort", "recordset-filter", "recordset-indexer" ] }, "recordset-base": { "requires": [ "base", "arraylist" ] }, "recordset-filter": { "requires": [ "recordset-base", "array-extras", "plugin" ] }, "recordset-indexer": { "requires": [ "recordset-base", "plugin" ] }, "recordset-sort": { "requires": [ "arraysort", "recordset-base", "plugin" ] }, "resize": { "use": [ "resize-base", "resize-proxy", "resize-constrain" ] }, "resize-base": { "requires": [ "base", "widget", "substitute", "event", "oop", "dd-drag", "dd-delegate", "dd-drop" ], "skinnable": true }, "resize-constrain": { "requires": [ "plugin", "resize-base" ] }, "resize-plugin": { "optional": [ "resize-constrain" ], "requires": [ "resize-base", "plugin" ] }, "resize-proxy": { "requires": [ "plugin", "resize-base" ] }, "rls": { "requires": [ "get", "features" ] }, "scrollview": { "requires": [ "scrollview-base", "scrollview-scrollbars" ] }, "scrollview-base": { "requires": [ "widget", "event-gestures", "transition" ], "skinnable": true }, "scrollview-base-ie": { "condition": { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }, "requires": [ "scrollview-base" ] }, "scrollview-paginator": { "requires": [ "plugin" ] }, "scrollview-scrollbars": { "requires": [ "classnamemanager", "transition", "plugin" ], "skinnable": true }, "selection": { "requires": [ "node" ] }, "selector": { "requires": [ "selector-native" ] }, "selector-css2": { "condition": { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }, "requires": [ "selector-native" ] }, "selector-css3": { "requires": [ "selector-native", "selector-css2" ] }, "selector-native": { "requires": [ "dom-base" ] }, "shim-plugin": { "requires": [ "node-style", "node-pluginhost" ] }, "slider": { "use": [ "slider-base", "slider-value-range", "clickable-rail", "range-slider" ] }, "slider-base": { "requires": [ "widget", "dd-constrain", "substitute" ], "skinnable": true }, "slider-value-range": { "requires": [ "slider-base" ] }, "sortable": { "requires": [ "dd-delegate", "dd-drop-plugin", "dd-proxy" ] }, "sortable-scroll": { "requires": [ "dd-scroll", "sortable" ] }, "stylesheet": {}, "substitute": { "optional": [ "dump" ] }, "swf": { "requires": [ "event-custom", "node", "swfdetect" ] }, "swfdetect": {}, "tabview": { "requires": [ "widget", "widget-parent", "widget-child", "tabview-base", "node-pluginhost", "node-focusmanager" ], "skinnable": true }, "tabview-base": { "requires": [ "node-event-delegate", "classnamemanager", "skin-sam-tabview" ] }, "tabview-plugin": { "requires": [ "tabview-base" ] }, "test": { "requires": [ "event-simulate", "event-custom", "substitute", "json-stringify" ], "skinnable": true }, "text": { "use": [ "text-accentfold", "text-wordbreak" ] }, "text-accentfold": { "requires": [ "array-extras", "text-data-accentfold" ] }, "text-data-accentfold": {}, "text-data-wordbreak": {}, "text-wordbreak": { "requires": [ "array-extras", "text-data-wordbreak" ] }, "transition": { "use": [ "transition-native", "transition-timer" ] }, "transition-native": { "requires": [ "node-base" ] }, "transition-timer": { "requires": [ "transition-native", "node-style" ] }, "uploader": { "requires": [ "event-custom", "node", "base", "swf" ] }, "view": { "requires": [ "base-build", "node-event-delegate" ] }, "widget": { "skinnable": true, "use": [ "widget-base", "widget-htmlparser", "widget-uievents", "widget-skin" ] }, "widget-anim": { "requires": [ "plugin", "anim-base", "widget" ] }, "widget-autohide": { "requires": [ "widget", "plugin", "event-outside", "base-build" ], "skinnable": false }, "widget-base": { "requires": [ "attribute", "event-focus", "base-base", "base-pluginhost", "node-base", "node-style", "classnamemanager" ] }, "widget-base-ie": { "condition": { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }, "requires": [ "widget-base" ] }, "widget-child": { "requires": [ "base-build", "widget" ] }, "widget-htmlparser": { "requires": [ "widget-base" ] }, "widget-locale": { "requires": [ "widget-base" ] }, "widget-modality": { "requires": [ "widget", "plugin", "event-outside", "base-build" ], "skinnable": false }, "widget-parent": { "requires": [ "base-build", "arraylist", "widget" ] }, "widget-position": { "requires": [ "base-build", "node-screen", "widget" ] }, "widget-position-align": { "requires": [ "widget-position" ] }, "widget-position-constrain": { "requires": [ "widget-position" ] }, "widget-skin": { "requires": [ "widget-base" ] }, "widget-stack": { "requires": [ "base-build", "widget" ], "skinnable": true }, "widget-stdmod": { "requires": [ "base-build", "widget" ] }, "widget-uievents": { "requires": [ "widget-base", "node-event-delegate" ] }, "yql": { "requires": [ "jsonp", "jsonp-url" ] }, "yui": { "use": [ "yui-base", "get", "features", "intl-base", "yui-log", "yui-later", "loader-base", "loader-rollup", "loader-yui3" ] }, "yui-base": {}, "yui-later": { "requires": [ "yui-base" ] }, "yui-log": { "requires": [ "yui-base" ] }, "yui-rls": { "use": [ "yui-base", "get", "features", "intl-base", "rls", "yui-log", "yui-later" ] }, "yui-throttle": { "requires": [ "yui-base" ] } }; YUI.Env[Y.version].md5 = 'ea3b697e30a4b7bf0c41e10e098f5bab'; }, '@VERSION@' ,{requires:['loader-base']}); YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3' ]});
src/routes.js
DarkLicornor/personalWebsite
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Router from 'react-routing/src/Router'; import fetch from './core/fetch'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const query = `/graphql?query={content(path:"${state.path}"){path,title,content,component}}`; const response = await fetch(query); const { data } = await response.json(); return data && data.content && <ContentPage {...data.content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
admin/client/App/components/Navigation/Mobile/index.js
jstockwin/keystone
/** * The mobile navigation, displayed on screens < 768px */ import React from 'react'; import Transition from 'react-addons-css-transition-group'; import MobileSectionItem from './SectionItem'; const ESCAPE_KEY_CODE = 27; const MobileNavigation = React.createClass({ displayName: 'MobileNavigation', propTypes: { brand: React.PropTypes.string, currentListKey: React.PropTypes.string, currentSectionKey: React.PropTypes.string, sections: React.PropTypes.array.isRequired, signoutUrl: React.PropTypes.string, }, getInitialState () { return { barIsVisible: false, }; }, // Handle showing and hiding the menu based on the window size when // resizing componentDidMount () { this.handleResize(); window.addEventListener('resize', this.handleResize); }, componentWillUnmount () { window.removeEventListener('resize', this.handleResize); }, handleResize () { this.setState({ barIsVisible: window.innerWidth < 768, }); }, // Toggle the menu toggleMenu () { this[this.state.menuIsVisible ? 'hideMenu' : 'showMenu'](); }, // Show the menu showMenu () { this.setState({ menuIsVisible: true, }); // Make the body unscrollable, so you can only scroll in the menu document.body.style.overflow = 'hidden'; document.body.addEventListener('keyup', this.handleEscapeKey, false); }, // Hide the menu hideMenu () { this.setState({ menuIsVisible: false, }); // Make the body scrollable again document.body.style.overflow = null; document.body.removeEventListener('keyup', this.handleEscapeKey, false); }, // If the escape key was pressed, hide the menu handleEscapeKey (event) { if (event.which === ESCAPE_KEY_CODE) { this.hideMenu(); } }, renderNavigation () { if (!this.props.sections || !this.props.sections.length) return null; return this.props.sections.map((section) => { // Get the link and the classname const href = section.lists[0].external ? section.lists[0].path : `${Keystone.adminPath}/${section.lists[0].path}`; const className = (this.props.currentSectionKey && this.props.currentSectionKey === section.key) ? 'MobileNavigation__section is-active' : 'MobileNavigation__section'; // Render a SectionItem return ( <MobileSectionItem key={section.key} className={className} href={href} lists={section.lists} currentListKey={this.props.currentListKey} onClick={this.toggleMenu} > {section.label} </MobileSectionItem> ); }); }, // Render a blockout renderBlockout () { if (!this.state.menuIsVisible) return null; return <div className="MobileNavigation__blockout" onClick={this.toggleMenu} />; }, // Render the sidebar menu renderMenu () { if (!this.state.menuIsVisible) return null; return ( <nav className="MobileNavigation__menu"> <div className="MobileNavigation__sections"> {this.renderNavigation()} </div> </nav> ); }, render () { if (!this.state.barIsVisible) return null; return ( <div className="MobileNavigation"> <div className="MobileNavigation__bar"> <button type="button" onClick={this.toggleMenu} className="MobileNavigation__bar__button MobileNavigation__bar__button--menu" > <span className={'MobileNavigation__bar__icon octicon octicon-' + (this.state.menuIsVisible ? 'x' : 'three-bars')} /> </button> <span className="MobileNavigation__bar__label"> {this.props.brand} </span> <a href={this.props.signoutUrl} className="MobileNavigation__bar__button MobileNavigation__bar__button--signout" > <span className="MobileNavigation__bar__icon octicon octicon-sign-out" /> </a> </div> <div className="MobileNavigation__bar--placeholder" /> <Transition transitionName="MobileNavigation__menu" transitionEnterTimeout={260} transitionLeaveTimeout={200} > {this.renderMenu()} </Transition> <Transition transitionName="react-transitiongroup-fade" transitionEnterTimeout={0} transitionLeaveTimeout={0} > {this.renderBlockout()} </Transition> </div> ); }, }); module.exports = MobileNavigation;
ajax/libs/jquery-footable/0.1.0/js/footable.js
ahocevar/cdnjs
/*! * FooTable - Awesome Responsive Tables * http://themergency.com/footable * * Requires jQuery - http://jquery.com/ * * Copyright 2012 Steven Usher & Brad Vincent * Released under the MIT license * You are free to use FooTable in commercial projects as long as this copyright header is left intact. * * Date: 18 Nov 2012 */ (function ($, w, undefined) { w.footable = { options: { delay: 100, // The number of millseconds to wait before triggering the react event breakpoints: { // The different screen resolution breakpoints phone: 480, tablet: 1024 }, parsers: { // The default parser to parse the value out of a cell (values are used in building up row detail) alpha: function (cell) { return $(cell).data('value') || $.trim($(cell).text()); } }, toggleSelector: ' > tbody > tr:not(.footable-row-detail)', //the selector to show/hide the detail row createDetail: function (element, data) { //creates the contents of the detail row for (var i = 0; i < data.length; i++) { element.append('<div><strong>' + data[i].name + '</strong> : ' + data[i].display + '</div>'); } }, classes: { loading : 'footable-loading', loaded : 'footable-loaded', sorted : 'footable-sorted', descending : 'footable-sorted-desc', indicator : 'footable-sort-indicator' }, debug: false // Whether or not to log information to the console. }, version: { major: 0, minor: 1, toString: function () { return w.footable.version.major + '.' + w.footable.version.minor; }, parse: function (str) { version = /(\d+)\.?(\d+)?\.?(\d+)?/.exec(str); return { major: parseInt(version[1]) || 0, minor: parseInt(version[2]) || 0, patch: parseInt(version[3]) || 0 }; } }, plugins: { _validate: function (plugin) { ///<summary>Simple validation of the <paramref name="plugin"/> to make sure any members called by Foobox actually exist.</summary> ///<param name="plugin">The object defining the plugin, this should implement a string property called "name" and a function called "init".</param> if (typeof plugin['name'] !== 'string') { if (w.footable.options.debug == true) console.error('Validation failed, plugin does not implement a string property called "name".', plugin); return false; } if (!$.isFunction(plugin['init'])) { if (w.footable.options.debug == true) console.error('Validation failed, plugin "' + plugin['name'] + '" does not implement a function called "init".', plugin); return false; } if (w.footable.options.debug == true) console.log('Validation succeeded for plugin "' + plugin['name'] + '".', plugin); return true; }, registered: [], // An array containing all registered plugins. register: function (plugin, options) { ///<summary>Registers a <paramref name="plugin"/> and its default <paramref name="options"/> with Foobox.</summary> ///<param name="plugin">The plugin that should implement a string property called "name" and a function called "init".</param> ///<param name="options">The default options to merge with the Foobox's base options.</param> if (w.footable.plugins._validate(plugin)) { w.footable.plugins.registered.push(plugin); if (options != undefined && typeof options === 'object') $.extend(true, w.footable.options, options); if (w.footable.options.debug == true) console.log('Plugin "' + plugin['name'] + '" has been registered with the Foobox.', plugin); } }, init: function (instance) { ///<summary>Loops through all registered plugins and calls the "init" method supplying the current <paramref name="instance"/> of the Foobox as the first parameter.</summary> ///<param name="instance">The current instance of the Foobox that the plugin is being initialized for.</param> for(var i = 0; i < w.footable.plugins.registered.length; i++){ try { w.footable.plugins.registered[i]['init'](instance); } catch(err) { if (w.footable.options.debug == true) console.error(err); } } } } }; var instanceCount = 0; $.fn.footable = function(options) { ///<summary>The main constructor call to initialize the plugin using the supplied <paramref name="options"/>.</summary> ///<param name="options"> ///<para>A JSON object containing user defined options for the plugin to use. Any options not supplied will have a default value assigned.</para> ///<para>Check the documentation or the default options object above for more information on available options.</para> ///</param> options=options||{}; var o=$.extend(true,{},w.footable.options,options); //merge user and default options return this.each(function () { instanceCount++; this.footable = new Footable(this, o, instanceCount); }); }; //helper for using timeouts function Timer() { ///<summary>Simple timer object created around a timeout.</summary> var t=this; t.id=null; t.busy=false; t.start=function (code,milliseconds) { ///<summary>Starts the timer and waits the specified amount of <paramref name="milliseconds"/> before executing the supplied <paramref name="code"/>.</summary> ///<param name="code">The code to execute once the timer runs out.</param> ///<param name="milliseconds">The time in milliseconds to wait before executing the supplied <paramref name="code"/>.</param> if (t.busy) {return;} t.stop(); t.id=setTimeout(function () { code(); t.id=null; t.busy=false; },milliseconds); t.busy=true; }; t.stop=function () { ///<summary>Stops the timer if its runnning and resets it back to its starting state.</summary> if(t.id!=null) { clearTimeout(t.id); t.id=null; t.busy=false; } }; }; function Footable(t, o, id) { ///<summary>Inits a new instance of the plugin.</summary> ///<param name="t">The main table element to apply this plugin to.</param> ///<param name="o">The options supplied to the plugin. Check the defaults object to see all available options.</param> ///<param name="id">The id to assign to this instance of the plugin.</param> var ft = this; ft.id = id; ft.table = t; ft.options = o; ft.breakpoints = []; ft.breakpointNames = ''; ft.columns = { }; var opt = ft.options; var cls = opt.classes; // This object simply houses all the timers used in the footable. ft.timers = { resize: new Timer(), register: function (name) { ft.timers[name] = new Timer(); return ft.timers[name]; } }; w.footable.plugins.init(ft); ft.init = function() { var $window = $(w), $table = $(ft.table); if ($table.hasClass(cls.loaded)) { //already loaded FooTable for the table, so don't init again ft.raise('footable_already_initialized'); return; } $table.addClass(cls.loading); // Get the column data once for the life time of the plugin $table.find('> thead > tr > th, > thead > tr > td').each(function() { var data = ft.getColumnData(this); ft.columns[data.index] = data; var count = data.index + 1; //get all the cells in the column var $column = $table.find('> tbody > tr > td:nth-child(' + count + ')'); //add the className to the cells specified by data-class="blah" if (data.className != null) $column.not('.footable-cell-detail').addClass(data.className); }); // Create a nice friendly array to work with out of the breakpoints object. for(var name in opt.breakpoints) { ft.breakpoints.push({ 'name': name, 'width': opt.breakpoints[name] }); ft.breakpointNames += (name + ' '); } // Sort the breakpoints so the smallest is checked first ft.breakpoints.sort(function(a, b) { return a['width'] - b['width']; }); //bind the toggle selector click events ft.bindToggleSelectors(); ft.raise('footable_initializing'); $table.bind('footable_initialized', function (e) { //resize the footable onload ft.resize(); //remove the loading class $table.removeClass(cls.loading); //hides all elements within the table that have the attribute data-hide="init" $table.find('[data-init="hide"]').hide(); $table.find('[data-init="show"]').show(); //add the loaded class $table.addClass(cls.loaded); }); $window .bind('resize.footable', function () { ft.timers.resize.stop(); ft.timers.resize.start(function() { ft.raise('footable_resizing'); ft.resize(); ft.raise('footable_resized'); }, opt.delay); }); ft.raise('footable_initialized'); }; //moved this out into it's own function so that it can be called from other add-ons ft.bindToggleSelectors = function() { var $table = $(ft.table); $table.find(opt.toggleSelector).unbind('click.footable').bind('click.footable', function (e) { if ($table.is('.breakpoint')) { var $row = $(this).is('tr') ? $(this) : $(this).parents('tr:first'); ft.toggleDetail($row.get(0)); } }); }; ft.parse = function(cell, column) { var parser = opt.parsers[column.type] || opt.parsers.alpha; return parser(cell); }; ft.getColumnData = function(th) { var $th = $(th), hide = $th.data('hide'); hide = hide || ''; hide = hide.split(','); var data = { 'index': $th.index(), 'hide': { }, 'type': $th.data('type') || 'alpha', 'name': $th.data('name') || $.trim($th.text()), 'ignore': $th.data('ignore') || false, 'className': $th.data('class') || null }; data.hide['default'] = ($th.data('hide')==="all") || ($.inArray('default', hide) >= 0); for(var name in opt.breakpoints) { data.hide[name] = ($th.data('hide')==="all") || ($.inArray(name, hide) >= 0); } var e = ft.raise('footable_column_data', { 'column': { 'data': data, 'th': th } }); return e.column.data; }; ft.getViewportWidth = function() { return window.innerWidth || (document.body ? document.body.offsetWidth : 0); }; ft.getViewportHeight = function() { return window.innerHeight || (document.body ? document.body.offsetHeight : 0); }; ft.hasBreakpointColumn = function(breakpoint) { for(var c in ft.columns) { if (ft.columns[c].hide[breakpoint]) { return true; } } return false; }; ft.resize = function() { var $table = $(ft.table); var info = { 'width': $table.width(), //the table width 'height': $table.height(), //the table height 'viewportWidth': ft.getViewportWidth(), //the width of the viewport 'viewportHeight': ft.getViewportHeight(), //the width of the viewport 'orientation': null }; info.orientation = info.viewportWidth > info.viewportHeight ? 'landscape' : 'portrait'; if (info.viewportWidth < info.width) info.width = info.viewportWidth; if (info.viewportHeight < info.height) info.height = info.viewportHeight; var pinfo = $table.data('footable_info'); $table.data('footable_info', info); // This (if) statement is here purely to make sure events aren't raised twice as mobile safari seems to do if (!pinfo || ((pinfo && pinfo.width && pinfo.width != info.width) || (pinfo && pinfo.height && pinfo.height != info.height))) { var current = null, breakpoint; for (var i = 0; i < ft.breakpoints.length; i++) { breakpoint = ft.breakpoints[i]; if (breakpoint && breakpoint.width && info.width <= breakpoint.width) { current = breakpoint; break; } } var breakpointName = (current == null ? 'default' : current['name']); var hasBreakpointFired = ft.hasBreakpointColumn(breakpointName); $table .removeClass('default breakpoint').removeClass(ft.breakpointNames) .addClass(breakpointName + (hasBreakpointFired ? ' breakpoint' : '')) .find('> thead > tr > th').each(function() { var data = ft.columns[$(this).index()]; var count = data.index + 1; //get all the cells in the column var $column = $table.find('> tbody > tr > td:nth-child(' + count + '), > tfoot > tr > td:nth-child(' + count + '), > colgroup > col:nth-child(' + count + ')').add(this); if (data.hide[breakpointName] == false) $column.show(); else $column.hide(); }) .end() .find('> tbody > tr.footable-detail-show').each(function() { ft.createOrUpdateDetailRow(this); }); $table.find('> tbody > tr.footable-detail-show:visible').each(function() { var $next = $(this).next(); if ($next.hasClass('footable-row-detail')) { if (breakpointName == 'default' && !hasBreakpointFired) $next.hide(); else $next.show(); } }); ft.raise('footable_breakpoint_' + breakpointName, { 'info': info }); } }; ft.toggleDetail = function(actualRow) { var $row = $(actualRow), created = ft.createOrUpdateDetailRow($row.get(0)), $next = $row.next(); if (!created && $next.is(':visible')) { $row.removeClass('footable-detail-show'); $next.hide(); } else { $row.addClass('footable-detail-show'); $next.show(); } }; ft.createOrUpdateDetailRow = function (actualRow) { var $row = $(actualRow), $next = $row.next(), $detail, values = []; if ($row.is(':hidden')) return; //if the row is hidden for some readon (perhaps filtered) then get out of here $row.find('> td:hidden').each(function () { var column = ft.columns[$(this).index()]; if (column.ignore == true) return true; values.push({ 'name': column.name, 'value': ft.parse(this, column), 'display': $.trim($(this).html()) }); }); var colspan = $row.find('> td:visible').length; var exists = $next.hasClass('footable-row-detail'); if (!exists) { // Create $next = $('<tr class="footable-row-detail"><td class="footable-cell-detail"><div class="footable-row-detail-inner"></div></td></tr>'); $row.after($next); } $next.find('> td:first').attr('colspan', colspan); $detail = $next.find('.footable-row-detail-inner').empty(); opt.createDetail($detail, values); return !exists; }; ft.raise = function(eventName, args) { args = args || { }; var def = { 'ft': ft }; $.extend(true, def, args); var e = $.Event(eventName, def); if (!e.ft) { $.extend(true, e, def); } //pre jQuery 1.6 which did not allow data to be passed to event object constructor $(ft.table).trigger(e); return e; }; ft.init(); return ft; }; })(jQuery, window);
definitions/npm/react-redux_v5.x.x/flow_v0.30.x-v0.52.x/test_Provider.js
echenley/flow-typed
// @flow import React from 'react' import { Provider } from 'react-redux' // $ExpectError <Provider />; // missing store
src/components/books/preview/BookPreviewFooter.js
great-design-and-systems/cataloguing-app
import { FontAwesome, ResponsiveButton } from '../../common/'; import { LABEL_ADD_BOOK, LABEL_CLOSE } from '../../../labels/'; import PropTypes from 'prop-types'; import React from 'react'; export const BookPreviewFooter = ({ closeDialog, addBook, readOnly }) => { return (<div className="btn-group btn-md"> {!readOnly && <ResponsiveButton onClick={addBook} className="btn btn-success" label={LABEL_ADD_BOOK} icon={ <FontAwesome name="plus" fixedWidth={true} size="lg" />} /> } <ResponsiveButton onClick={closeDialog} className="btn btn-danger" label={LABEL_CLOSE} icon={ <FontAwesome name="close" fixedWidth={true} size="lg" /> } /> </div>); }; BookPreviewFooter.propTypes = { readOnly: PropTypes.bool, addBook: PropTypes.func, closeDialog: PropTypes.func.isRequired };
src/svg-icons/file/cloud-download.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCloudDownload = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM17 13l-5 5-5-5h3V9h4v4h3z"/> </SvgIcon> ); FileCloudDownload = pure(FileCloudDownload); FileCloudDownload.displayName = 'FileCloudDownload'; FileCloudDownload.muiName = 'SvgIcon'; export default FileCloudDownload;
src/templates/project-page.js
michaeltmiller/michaelmiller.io
import React from 'react'; import Carousel from '../components/carousel'; import Iphone from '../components/iphone'; import Macbook from '../components/macbook'; import OutboundLink from '../components/outbound-link'; import Wrapper from '../components/wrapper'; import { ProjectDescription, ProjectIntro, ProjectPage } from '../components/project'; import styles from './styles.module.css'; export default ({ data, location }) => { const icon = require(`./img/${data.projectsJson.cover.source}.png`) const images = [ { src: require(`./img/${data.projectsJson.images.image1}.png`), description: 'image' }, { src: require(`./img/${data.projectsJson.images.image2}.png`), description: 'image2' }, { src: require(`./img/${data.projectsJson.images.image3}.png`), description: 'image4' }, { src: require(`./img/${data.projectsJson.images.image4}.png`), description: 'image3' }, { src: require(`./img/${data.projectsJson.images.image5}.png`), description: 'image5' } ] const image = ( <div className={styles.image}> <img src={icon} alt={data.projectsJson.cover.alternative} /> </div> ); const techused= ( <aside className={styles.skills}> <div> <h3>Tech Used:</h3> <h4>Presentation</h4> <p>{data.projectsJson.tech.presentation}</p> <h4>Javascript</h4> <p>{data.projectsJson.tech.javascript}</p> <h4>Server</h4> <p>{data.projectsJson.tech.server}</p> <h4>Other</h4> <p>{data.projectsJson.tech.other}</p> </div> </aside> ) return ( <ProjectPage project={data.projectsJson} location={location}> <ProjectIntro project={data.projectsJson} media={image} /> <ProjectDescription media={techused} project={data.projectsJson}> </ProjectDescription> <Wrapper> <Macbook> <Carousel images={images} /> </Macbook> </Wrapper> </ProjectPage> ); }; export const query = graphql` query ProjectPageQuery($slug: String!) { projectsJson(slug: {eq: $slug}){ className description text title images{ image1 image2 image3 image4 image5 } tech{ presentation javascript server other } links{ website repo } slug theme{ background light } cover{ source alternative } } } `
indico/web/client/js/jquery/widgets/jinja/permissions_widget.js
pferreir/indico
// This file is part of Indico. // Copyright (C) 2002 - 2021 CERN // // Indico is free software; you can redistribute it and/or // modify it under the terms of the MIT License; see the // LICENSE file for more details. import React from 'react'; import ReactDOM from 'react-dom'; import {GroupSearch, UserSearch} from 'indico/react/components/principals/Search'; import {PrincipalType} from 'indico/react/components/principals/util'; import {FavoritesProvider} from 'indico/react/hooks'; import {Translate} from 'indico/react/i18n'; import Palette from 'indico/utils/palette'; (function($) { const FULL_ACCESS_PERMISSIONS = '_full_access'; const READ_ACCESS_PERMISSIONS = '_read_access'; $.widget('indico.permissionswidget', { options: { objectType: null, permissionsInfo: null, hiddenPermissions: null, hiddenPermissionsInfo: null, }, _update() { // Sort entries aphabetically and by type this.data = _.chain(this.data) .sortBy(item => item[0].name || item[0].id) .sortBy(item => item[0]._type) .value(); // Sort permissions alphabetically this.data.forEach(item => { item[1].sort(); }); this.$dataField.val(JSON.stringify(this.data)); this.element.trigger('change'); }, _renderRoleCode(code, color) { return $('<span>', { class: 'role-code', text: code, css: { borderColor: `#${color}`, color: `#${color}`, }, }); }, _renderLabel(principal) { const $labelBox = $('<div>', {class: 'label-box flexrow f-a-center'}); const type = principal._type; if (type === 'EventRole') { $labelBox.append(this._renderEventRoleLabel(principal)); } else if (type === 'CategoryRole') { $labelBox.append(this._renderCategoryRoleLabel(principal)); } else { $labelBox.append(this._renderOtherLabel(principal, type)); } return $labelBox; }, _renderEventRoleLabel(principal) { const $text = $('<span>', { 'class': 'text-normal entry-label', 'text': principal.name, 'data-tooltip-text': principal.name, }); const $code = this._renderRoleCode(principal.code, principal.color); return [$code, $text]; }, _renderCategoryRoleLabel(principal) { const text = principal.name; const extraText = principal.category; const $code = this._renderRoleCode(principal.code, principal.color); const tooltip = `${text} (${extraText})`; const textDiv = $('<div>', { 'class': 'text-normal entry-label', 'data-tooltip-text': tooltip, }); textDiv.append($('<span>', {text})); textDiv.append('<br>'); textDiv.append($('<span>', {class: 'text-not-important entry-label-extra', text: extraText})); return [$code, textDiv]; }, _renderOtherLabel(principal, type) { let iconClass, extraText; if (type === 'Avatar') { iconClass = 'icon-user'; extraText = principal.email; } else if (type === 'Email') { iconClass = 'icon-mail'; } else if (type === 'DefaultEntry' && principal.id === 'anonymous') { iconClass = 'icon-question'; } else if (type === 'IPNetworkGroup') { iconClass = 'icon-lan'; } else if (type === 'RegistrationForm') { iconClass = 'icon-ticket'; } else if (type === 'LocalGroup') { iconClass = 'icon-users'; } else if (type === 'MultipassGroup') { iconClass = 'icon-users'; extraText = principal.provider_title; } else { iconClass = 'icon-users'; } const text = principal.name; const tooltip = extraText ? `${text} (${extraText})` : text; const textDiv = $('<div>', { 'class': 'text-normal entry-label', 'data-tooltip-text': tooltip, }); textDiv.append($('<span>', {text})); if (extraText) { textDiv.append('<br>'); textDiv.append( $('<span>', {class: 'text-not-important entry-label-extra', text: extraText}) ); } return [$('<span>', {class: `entry-icon ${iconClass}`}), textDiv]; }, _renderPermissions(principal, permissions) { const $permissions = $('<div>', {class: 'permissions-box flexrow f-a-center f-self-stretch'}); const $permissionsList = $('<ul>').appendTo($permissions); // When full access is enabled, always show read access if ( _.contains(permissions, FULL_ACCESS_PERMISSIONS) && !_.contains(permissions, READ_ACCESS_PERMISSIONS) ) { permissions.push(READ_ACCESS_PERMISSIONS); if (principal._type !== 'DefaultEntry' && principal._type !== 'AdditionalUsers') { this._updateItem(principal, permissions); } } permissions.forEach(item => { const permissionInfo = this.options.permissionsInfo[item]; const applyOpacity = item === READ_ACCESS_PERMISSIONS && _.contains(permissions, FULL_ACCESS_PERMISSIONS) && principal._type !== 'DefaultEntry'; const cssClasses = (applyOpacity ? 'disabled ' : '') + (permissionInfo.color ? `color-${permissionInfo.color} ` : '') + (permissionInfo.css_class ? `${permissionInfo.css_class} ` : ''); $permissionsList.append( $('<li>', { class: `i-label bold ${cssClasses}`, title: permissionInfo.description, }).append(permissionInfo.title) ); }); if (principal._type !== 'DefaultEntry' && principal._type !== 'AdditionalUsers') { $permissions.append(this._renderPermissionsButtons(principal, permissions)); } return $permissions; }, _renderPermissionsButtons(principal, permissions) { const $buttonsGroup = $('<div>', {class: 'group flexrow'}); $buttonsGroup.append( this._renderEditBtn(principal, permissions), this._renderDeleteBtn(principal) ); return $buttonsGroup; }, _renderEditBtn(principal, permissions) { if (principal._type === 'IPNetworkGroup' || principal._type === 'RegistrationForm') { const title = { IPNetworkGroup: $T.gettext('IP networks cannot have management permissions'), RegistrationForm: $T.gettext('Registrants cannot have management permissions'), }[principal._type]; return $('<button>', { type: 'button', class: 'i-button text-color borderless icon-only icon-edit disabled', title, }); } else { return $('<button>', { 'type': 'button', 'class': 'i-button text-color borderless icon-only icon-edit', 'data-href': build_url(Indico.Urls.PermissionsDialog, {type: this.options.objectType}), 'data-title': $T.gettext('Assign Permissions'), 'data-method': 'POST', 'data-ajax-dialog': '', 'data-params': JSON.stringify({principal: JSON.stringify(principal), permissions}), }); } }, _renderDeleteBtn(principal) { const self = this; return $('<button>', { 'type': 'button', 'class': 'i-button text-color borderless icon-only icon-remove', 'data-principal': JSON.stringify(principal), }).on('click', function() { const $this = $(this); let confirmed; if (principal._type === 'Avatar' && principal.id === $('body').data('user-id')) { const title = $T.gettext("Delete entry '{0}'".format(principal.name || principal.id)); const message = $T.gettext('Are you sure you want to remove yourself from the list?'); confirmed = confirmPrompt(message, title); } else { confirmed = $.Deferred().resolve(); } confirmed.then(() => { self._updateItem($this.data('principal'), []); }); }); }, _renderItem(item) { const $item = $('<li>', {class: 'flexrow f-a-center'}); const [principal, permissions] = item; $item.append(this._renderLabel(principal)); $item.append(this._renderPermissions(principal, permissions)); $item.toggleClass(`disabled ${principal.id}`, principal._type === 'DefaultEntry'); return $item; }, _renderHiddenPermissions(item) { const $item = $('<li>', { class: 'flexrow f-a-center', }); const [principal, description, $permissionsList] = item; $permissionsList.hide(); const $dropdownButton = $('<button>', { type: 'button', class: 'i-button text-color borderless icon-only icon-expand hidden-permissions-icon', }).on('click', () => { $permissionsList.toggle(); $dropdownButton.toggleClass('icon-expand icon-collapse'); }); const $hiddenPermissionsDiv = $('<div>', { class: 'permissions-box f-a-center f-self-stretch', }); const $descriptionDiv = $('<div>', {class: 'flexrow f-a-center'}); $descriptionDiv.append( $('<div>', {class: 'hidden-permissions-description', text: description}) ); $descriptionDiv.append($dropdownButton); $hiddenPermissionsDiv.append($descriptionDiv); $hiddenPermissionsDiv.append($permissionsList); $item.append(this._renderLabel(principal).toggleClass(`disabled ${principal.id}`)); $item.append($hiddenPermissionsDiv); return $item; }, _renderHiddenPermissionsList(hiddenUserPermissions, permissionsInfo) { const $list = $('<ul>', {class: 'hidden-permissions-list'}); hiddenUserPermissions.forEach(([name, perms]) => { const permissionList = perms .map(x => permissionsInfo[x]) .filter(x => x !== null) .join(', '); const $user = $('<strong />', {text: name}); const $permissions = `: ${permissionList}`; const $entry = $('<li>') .append($user) .append($permissions); $list.append($entry); }); return $list; }, _renderDropdown($dropdown, getText = null) { $dropdown.children(':not(.default)').remove(); $dropdown.parent().dropdown({ selector: '.js-dropdown', }); const $dropdownLink = $dropdown.prev('.js-dropdown'); const items = $dropdown.data('items'); const isRoleDropdown = $dropdown.hasClass('entry-role-dropdown'); items.forEach(item => { if (this._findEntryIndex(item) === -1) { if (isRoleDropdown) { $dropdown.find('.separator').before(this._renderDropdownItem(item, getText)); } else { $dropdown.append(this._renderDropdownItem(item, getText)); } } }); if (isRoleDropdown) { const isEmpty = !$dropdown.children().not('.default').length; $('.entry-role-dropdown .separator').toggleClass('hidden', isEmpty); } else if (!$dropdown.children().length) { $dropdownLink.addClass('disabled').attr('title', $T.gettext('All options have been added')); } else { $dropdownLink.removeClass('disabled'); } }, _renderDropdownItem(principal, getText) { const self = this; const $dropdownItem = $('<li>', { 'class': 'entry-item', 'data-principal': JSON.stringify(principal), }); const $itemContent = $('<a>'); if (principal._type === 'EventRole' || principal._type === 'CategoryRole') { $itemContent.append( this._renderRoleCode(principal.code, principal.color).addClass('dropdown-icon') ); } const $text = $('<span>', {text: getText ? getText(principal.name) : principal.name}); $dropdownItem.append($itemContent.append($text)).on('click', function() { // Grant read access by default self._addItems([$(this).data('principal')], [READ_ACCESS_PERMISSIONS]); }); return $dropdownItem; }, _renderDuplicatesTooltip(idx) { this.$permissionsWidgetList .find('>li') .not('.disabled') .eq(idx) .qtip({ content: { text: $T.gettext('This entry was already added'), }, show: { ready: true, effect() { $(this).fadeIn(300); }, }, hide: { event: 'unfocus click', }, events: { hide() { $(this).fadeOut(300); $(this).qtip('destroy'); }, }, position: { my: 'center left', at: 'center right', }, style: { classes: 'qtip-warning', }, }); }, _render() { this.$permissionsWidgetList.empty(); this.data.forEach(item => { this.$permissionsWidgetList.append(this._renderItem(item)); }); // Add default entries const anonymous = [ {_type: 'DefaultEntry', name: $T.gettext('Anonymous'), id: 'anonymous'}, [READ_ACCESS_PERMISSIONS], ]; this.$permissionsWidgetList.append(this._renderItem(anonymous)); if (this.options.hiddenPermissions.length > 0) { const additionalPermissions = [ { _type: 'AdditionalUsers', name: $T.gettext('Additional users'), id: 'additional', }, $T .ngettext( '{0} user has implicit read access due to other roles', '{0} users have implicit read access due to other roles', this.options.hiddenPermissions.length ) .format(this.options.hiddenPermissions.length), this._renderHiddenPermissionsList( this.options.hiddenPermissions, this.options.hiddenPermissionsInfo ), ]; this.$permissionsWidgetList.append(this._renderHiddenPermissions(additionalPermissions)); } let managersTitle; if (this.options.objectType === 'event') { managersTitle = $T.gettext('Category Managers'); } else if (this.options.objectType === 'category') { managersTitle = $T.gettext('Parent Category Managers'); } else { managersTitle = $T.gettext('Event Managers'); } const managers = [{_type: 'DefaultEntry', name: managersTitle}, [FULL_ACCESS_PERMISSIONS]]; this.$permissionsWidgetList.prepend(this._renderItem(managers)); this.$permissionsWidgetList.find('.anonymous').toggle(!this.isEventProtected); if (this.$eventRoleDropdown.length) { this._renderDropdown(this.$eventRoleDropdown); } if (this.$categoryRoleDropdown.length) { this._renderDropdown(this.$categoryRoleDropdown); } if (this.$ipNetworkDropdown.length) { this._renderDropdown(this.$ipNetworkDropdown); } if (this.$registrationFormDropdown.length) { this._renderDropdown(this.$registrationFormDropdown, name => $T.gettext('Registrants in "{0}"').format(name) ); } }, _findEntryIndex(principal) { return _.findIndex(this.data, item => item[0].identifier === principal.identifier); }, _updateItem(principal, newPermissions) { const idx = this._findEntryIndex(principal); if (newPermissions.length) { this.data[idx][1] = newPermissions; } else { this.data.splice(idx, 1); } this._update(); this._render(); }, _addItems(principals, permissions) { const news = []; const repeated = []; principals.forEach(principal => { const idx = this._findEntryIndex(principal); if (idx === -1) { this.data.push([principal, permissions]); news.push(principal); } else { repeated.push(principal); } }); this._update(); this._render(); news.forEach(principal => { this.$permissionsWidgetList .children('li:not(.disabled)') .eq(this._findEntryIndex(principal)) .effect('highlight', {color: Palette.highlight}, 'slow'); }); repeated.forEach(principal => { this._renderDuplicatesTooltip(this._findEntryIndex(principal)); }); }, _create() { this.$permissionsWidgetList = this.element.find('.permissions-widget-list'); this.$dataField = this.element.find('input[type=hidden]'); this.$eventRoleDropdown = this.element.find('.entry-role-dropdown'); this.$categoryRoleDropdown = this.element.find('.entry-category-role-dropdown'); this.$ipNetworkDropdown = this.element.find('.entry-ip-network-dropdown'); this.$registrationFormDropdown = this.element.find('.entry-reg-form-dropdown'); this.data = JSON.parse(this.$dataField.val()); this._update(); this._render(); // Manage changes on the permissions dialog this.element.on('indico:permissionsChanged', (evt, permissions, principal) => { this._updateItem(principal, permissions); }); // Manage changes on the event protection mode field this.element.on('indico:protectionModeChanged', (evt, isProtected) => { this.isEventProtected = isProtected; this._render(); }); // Manage adding users/groups to the acl const userSearchTrigger = triggerProps => ( <a className="i-button" {...triggerProps}> <Translate>User</Translate> </a> ); const groupSearchTrigger = triggerProps => ( <a className="i-button" {...triggerProps}> <Translate>Group</Translate> </a> ); const existing = JSON.parse(this.$dataField.val()).map(e => e[0].identifier); ReactDOM.render( <FavoritesProvider> {([favorites]) => ( <> <UserSearch favorites={favorites} existing={existing.filter(e => e.startsWith('User'))} onAddItems={e => { const items = e.map(({identifier, userId, name, firstName, lastName}) => ({ identifier, name, id: userId, familyName: lastName, firstName, _type: 'Avatar', })); this._addItems(items, [READ_ACCESS_PERMISSIONS]); }} triggerFactory={userSearchTrigger} /> <GroupSearch existing={existing.filter(e => e.startsWith('Group'))} onAddItems={e => { const items = e.map(({identifier, name, type, provider}) => { let id; if (type === PrincipalType.localGroup) { const splitIdentifier = identifier.split(':'); id = splitIdentifier[splitIdentifier.length - 1]; } else { id = name; } return { identifier, name, provider, _type: type === PrincipalType.localGroup ? 'LocalGroup' : 'MultipassGroup', id, }; }); this._addItems(items, [READ_ACCESS_PERMISSIONS]); }} triggerFactory={groupSearchTrigger} /> </> )} </FavoritesProvider>, document.getElementById('js-add-user-group') ); // Manage the creation of new roles $('.js-new-role').on('ajaxDialog:closed', (evt, data) => { if (data && data.role) { this.$eventRoleDropdown.data('items').push(data.role); this._addItems([data.role], [READ_ACCESS_PERMISSIONS]); } }); // Apply ellipsis + tooltip on long names this.$permissionsWidgetList.on('mouseenter', '.entry-label', function() { const $this = $(this); if (this.offsetWidth < this.scrollWidth && !$this.attr('title')) { $this.attr('title', $this.attr('data-tooltip-text')); } }); }, }); })(jQuery);
vibe-ui/src/components/__tests__/Message.js
3ll3d00d/vibe
import React from 'react'; import ReactDOM from 'react-dom'; import Message from '../Message'; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<Message />, div); });
fields/types/embedly/EmbedlyField.js
Yaska/keystone
import React from 'react'; import Field from '../Field'; import { FormField, FormInput } from 'elemental'; import ImageThumbnail from '../../components/ImageThumbnail'; import NestedFormField from '../../components/NestedFormField'; module.exports = Field.create({ displayName: 'EmbedlyField', statics: { type: 'Embedly', getDefaultValue: () => ({}), }, // always defers to renderValue; there is no form UI for this field renderField () { return this.renderValue(); }, renderValue (path, label, multiline) { return ( <NestedFormField key={path} label={label}> <FormInput noedit multiline={multiline}>{this.props.value[path]}</FormInput> </NestedFormField> ); }, renderAuthor () { if (!this.props.value.authorName) return; return ( <NestedFormField key="author" label="Author"> <FormInput noedit href={this.props.value.authorUrl && this.props.value.authorUrl} target="_blank">{this.props.value.authorName}</FormInput> </NestedFormField> ); }, renderDimensions () { if (!this.props.value.width || !this.props.value.height) return; return ( <NestedFormField key="dimensions" label="Dimensions"> <FormInput noedit>{this.props.value.width} &times; {this.props.value.height}px</FormInput> </NestedFormField> ); }, renderPreview () { if (!this.props.value.thumbnailUrl) return; var image = <img width={this.props.value.thumbnailWidth} height={this.props.value.thumbnailHeight} src={this.props.value.thumbnailUrl} />; var preview = this.props.value.url ? ( <ImageThumbnail component="a" href={this.props.value.url} target="_blank"> {image} </ImageThumbnail> ) : ( <ImageThumbnail>{image}</ImageThumbnail> ); return ( <NestedFormField label="Preview"> {preview} </NestedFormField> ); }, renderUI () { if (!this.props.value.exists) { return ( <FormField label={this.props.label}> <FormInput noedit>(not set)</FormInput> </FormField> ); } return ( <div> <FormField key="provider" label={this.props.label}> <FormInput noedit>{this.props.value.providerName} {this.props.value.type}</FormInput> </FormField> {this.renderValue('title', 'Title')} {this.renderAuthor()} {this.renderValue('description', 'Description', true)} {this.renderPreview()} {this.renderDimensions()} </div> ); }, });
node_modules/react-scripts/template/src/index.js
soniacq/LearningReact
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
app/routes.js
cdiezmoran/AlphaStage-desktop
/* eslint flowtype-errors/show-errors: 0 */ import React from 'react'; import { Switch, Route } from 'react-router'; import App from './containers/App'; import BrowsePage from './containers/BrowsePage'; import CreateGamePage from './containers/CreateGamePage'; import DashboardPage from './containers/DashboardPage'; import GamePage from './containers/GamePage'; import LibraryPage from './containers/LibraryPage'; export default () => ( <App> <Switch> <Route exact path="/" component={BrowsePage} /> <Route path="/games/new" component={CreateGamePage} /> <Route path="/games/library" component={LibraryPage} /> <Route path="/games/:id" component={GamePage} /> <Route path="/dashboard" component={DashboardPage} /> </Switch> </App> );
app/jsx/grading/AccountTabContainer.js
venturehive/canvas-lms
/* * Copyright (C) 2015 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import PropTypes from 'prop-types' import GradingStandardCollection from 'jsx/grading/gradingStandardCollection' import GradingPeriodSetCollection from 'jsx/grading/GradingPeriodSetCollection' import $ from 'jquery' import I18n from 'i18n!grading_periods' const { bool, string, shape } = PropTypes; class AccountTabContainer extends React.Component { static propTypes = { readOnly: bool.isRequired, urls: shape({ gradingPeriodSetsURL: string.isRequired, gradingPeriodsUpdateURL: string.isRequired, enrollmentTermsURL: string.isRequired, deleteGradingPeriodURL: string.isRequired }).isRequired, } componentDidMount () { $(this.tabContainer).children('.ui-tabs-minimal').tabs(); } render () { return ( <div ref={(el) => { this.tabContainer = el; }}> <h1>{I18n.t('Grading')}</h1> <div className="ui-tabs-minimal"> <ul> <li><a href="#grading-periods-tab" className="grading_periods_tab"> {I18n.t('Grading Periods')}</a></li> <li><a href="#grading-standards-tab" className="grading_standards_tab"> {I18n.t('Grading Schemes')}</a></li> </ul> <div ref={(el) => { this.gradingPeriods = el; }} id="grading-periods-tab" > <GradingPeriodSetCollection urls={this.props.urls} readOnly={this.props.readOnly} /> </div> <div ref={(el) => { this.gradingStandards = el; }} id="grading-standards-tab" > <GradingStandardCollection /> </div> </div> </div> ); } } export default AccountTabContainer
src/client/activity/Activity.js
busyorg/busy
import React from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import { injectIntl } from 'react-intl'; import Affix from '../components/Utils/Affix'; import LeftSidebar from '../app/Sidebar/LeftSidebar'; import UserActivity from './UserActivity'; import RightSidebar from '../app/Sidebar/RightSidebar'; import requiresLogin from '../auth/requiresLogin'; const Activity = ({ intl }) => ( <div className="shifted"> <Helmet> <title>{intl.formatMessage({ id: 'activity', defaultMessage: 'Activity' })} - Busy</title> </Helmet> <div className="feed-layout container"> <Affix className="leftContainer" stickPosition={77}> <div className="left"> <LeftSidebar /> </div> </Affix> <Affix className="rightContainer" stickPosition={77}> <div className="right"> <RightSidebar /> </div> </Affix> <div className="center"> <UserActivity isCurrentUser /> </div> </div> </div> ); Activity.propTypes = { intl: PropTypes.shape().isRequired, }; export default requiresLogin(injectIntl(Activity));
frontend/src/Settings/MediaManagement/Naming/NamingOption.js
geogolem/Radarr
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Link from 'Components/Link/Link'; import { sizes } from 'Helpers/Props'; import styles from './NamingOption.css'; class NamingOption extends Component { // // Listeners onPress = () => { const { token, tokenSeparator, tokenCase, isFullFilename, onPress } = this.props; let tokenValue = token; tokenValue = tokenValue.replace(/ /g, tokenSeparator); if (tokenCase === 'lower') { tokenValue = token.toLowerCase(); } else if (tokenCase === 'upper') { tokenValue = token.toUpperCase(); } onPress({ isFullFilename, tokenValue }); } // // Render render() { const { token, tokenSeparator, example, tokenCase, isFullFilename, size } = this.props; return ( <Link className={classNames( styles.option, styles[size], styles[tokenCase], isFullFilename && styles.isFullFilename )} onPress={this.onPress} > <div className={styles.token}> {token.replace(/ /g, tokenSeparator)} </div> <div className={styles.example}> {example.replace(/ /g, tokenSeparator)} </div> </Link> ); } } NamingOption.propTypes = { token: PropTypes.string.isRequired, example: PropTypes.string.isRequired, tokenSeparator: PropTypes.string.isRequired, tokenCase: PropTypes.string.isRequired, isFullFilename: PropTypes.bool.isRequired, size: PropTypes.oneOf([sizes.SMALL, sizes.LARGE]), onPress: PropTypes.func.isRequired }; NamingOption.defaultProps = { size: sizes.SMALL, isFullFilename: false }; export default NamingOption;
app/client/src/routes/privacySecurity/index.js
uprisecampaigns/uprise-app
import React from 'react'; import PrivacySecurity from 'scenes/PrivacySecurity'; import Layout from 'components/Layout'; export default { path: '/settings/privacy-security', async action() { const privacyContent = await import(/* webpackChunkName: "privacy" */ 'content/privacy.md'); return { title: 'Privacy and Security', component: <Layout><PrivacySecurity privacyContent={privacyContent} /></Layout>, }; }, };
client/landing/components/donate/index.js
bryanph/Geist
import React from 'react' import ReactDom from 'react-dom' class Landing extends React.Component { constructor(props) { super(props) } render() { return ( <div> </div> ) } } export default Landing
packages/material-ui-icons/src/CardMembershipRounded.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M20 2H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h4v5l4-2 4 2v-5h4c1.11 0 2-.89 2-2V4c0-1.11-.89-2-2-2zm0 13H4v-2h16v2zm0-5H4V5c0-.55.45-1 1-1h14c.55 0 1 .45 1 1v5z" /></g></React.Fragment> , 'CardMembershipRounded');
src/app.js
chrisk8er/Simple-Electron-React-Boilerplate
import './main.css'; import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <h1>Hello World!</h1>, document.getElementById('root') );
JS Web/ReactJS/Event and Forms/src/components/form/formFields/Input.js
mitaka00/SoftUni
import React from 'react' import Valid from './../validationComponents/Valid' import Invalid from './../validationComponents/Invalid' let Input = props => { return ( <div> <label htmlFor={props.data}>{props.name}</label> <div> <input style={{ width: '300px' }} onChange={(e)=> props.func(e)} id={props.data} name={props.data} type={props.type} /> <Valid display={props.valid} /> <Invalid display={props.valid} /> </div> </div> ) } export default Input
src/routes.js
lyef/lyef-redux-boilerplate
import React from 'react'; import { Switch, Route } from 'react-router-dom'; import HelloWorld from 'views/HelloWorld'; // This is a class-based component because the current // version of hot reloading won't hot reload a stateless // component at the top-level. /* eslint-disable react/prefer-stateless-function */ class Routes extends React.Component { render() { return ( <Switch> <Route exact path="/" component={HelloWorld} /> </Switch> ); } } export default Routes;
addons/themes/story/layouts/Single.js
rendact/rendact
import React from 'react'; import Header from '../includes/Header'; import Footer from '../includes/Footer'; import FooterWidgets from '../includes/FooterWidgets'; class Single extends React.Component { componentDidMount(){ require('../assets/css/main.css') } render(){ let { postData, theConfig, title, image, content, isHome } = this.props; // debugger return ( <div id="wrapper" className="divided"> <Header name={theConfig ? theConfig.name : "Rendact"} tagline={theConfig ? theConfig.tagline: "hello"} {...this.props} /> <div id="main" className="wrapper style1" style={{backgroundColor: "#D3D3D3"}}> <div className="inner"> {postData && <section id="one"> <div className="inner"> <article> {!isHome && <header className="major"> <h1>{postData.title}</h1> </header> } <span className="image main"><img src={postData.imageFeatured ? postData.imageFeatured.blobUrl : require("images/logo-128.png") } alt=""/></span> <div dangerouslySetInnerHTML={{__html: postData.content}}/> </article> </div> </section> } </div> </div> <FooterWidgets {...this.props}/> <Footer /> </div> ) } } export default Single;
test/unit/testHelper.js
ChrisBauer/codenames-frontend
import jq from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import ReactTestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import createHistory from 'react-router/lib/browserHistory'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../../src/js/reducers'; // Global prerequisites to make it work in the command line global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; const $ = jq(window); // Set up chai-jquery chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = ReactTestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); // Produces HTML return $(ReactDOM.findDOMNode(componentInstance)); } function mockHistory(component) { component.childContextTypes = { history: React.PropTypes.object }; component.prototype.getChildContext = () => ({ history: createHistory() }); } // Helper for simulating events $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } ReactTestUtils.Simulate[eventName](this[0]); }; export { renderComponent, mockHistory, expect };
src/routes/catalog/Panel/Panel.js
pustovitDmytro/maysternya
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Panel.css'; import cx from 'classnames'; //function returns width of the i-th picture let elemW = function(n,i, prob=0.05,kof=1.3){ if (n==1) return 100; if (n>4) kof = 1.1; return 100*Math.pow(kof,i)*((kof-1)*(1-prob))/(Math.pow(kof,n)-1); } class Panel extends React.Component { render() { if(!this.props.source.length) return (<div>Unable to load data</div>); return ( <div> <div className={s.panel}> { this.props.source.map((elem,i,arr) => <img key={i} className={cx(s.Photo,"photo")} src={elem.img} alt={elem.alt} style={{width:elemW(arr.length,i)+"%"}}/> ) } </div> </div> ); } } export default withStyles(s)(Panel);
src/containers/flash/tests.js
thinktopography/reframe
import React from 'react' import { expect } from 'chai' import { shallow } from 'enzyme' import * as actions from './actions' import reducer from './reducer' import Flash from './flash' describe('flash component', () => { describe('actions', () => { it('can dispatch set', () => { const expected = { type: 'SET', style: 'success', message: 'good job' } expect(actions.set('success', 'good job')).to.eql(expected) }) it('can dispatch clear', () => { const expected = { type: 'CLEAR' } expect(actions.clear()).to.eql(expected) }) }) describe('reducer', () => { it('can set default state', () => { const expected = { message: null, style: null } expect(reducer(undefined, '')).to.eql(expected) }) it('can set flash message', () => { const state = { message: null, style: null } const action = { type: 'SET', style: 'success', message: 'good job' } const expected = { style: 'success', message: 'good job' } expect(reducer(state, action)).to.eql(expected) }) it('can clear flash message', () => { const state = { style: 'success', message: 'good job' } const action = { type: 'CLEAR' } const expected = { message: null, style: null } expect(reducer(state, action)).to.eql(expected) }) }) describe('component', () => { it('renders with a default state', () => { const config = { message: null, style: null, onSet: () => {}, onClear: () => {} } const flash = shallow( <Flash {...config}><div>child</div></Flash> ) expect(flash.is('div.reframe-flash')).to.be.true expect(flash.children.length).to.be.equal(1) const child = flash.childAt(0) expect(child.is('div')).to.be.truthy expect(child.text()).to.equal('child') }) it('renders with flash', () => { const config = { message: 'good job', style: 'success', onSet: () => {}, onClear: () => {} } const flash = shallow( <Flash {...config} /> ) const transitionGroup = flash.childAt(0) const popup = transitionGroup.childAt(0) expect(popup.is('div.reframe-flash-popup.success')).to.be.true const panel = popup.childAt(0) expect(panel.is('div.reframe-flash-popup-panel')).to.be.true const icon = panel.childAt(0) expect(icon.is('div.reframe-flash-popup-icon')).to.be.true expect(icon.childAt(0).is('i.fa.fa-check-circle')).to.be.true const message = panel.childAt(1) expect(message.is('div.reframe-flash-popup-message')).to.be.true const paragraph = message.childAt(0) expect(paragraph.is('p')).to.be.truthy expect(paragraph.text()).to.equal('good job') }) }) })
src/shared/utils/render-routes.js
rvboris/finalytics
import React from 'react'; import { Route, Switch, Redirect } from 'react-router-dom'; import uuid from 'uuid'; const checkAuth = (store, route, props) => { if (!route.auth) { return <route.component {...props} route={route} />; } const { isAuthenticated } = store.getState().auth; const { required, redirect, status } = route.auth; const isRedirect = (required && !isAuthenticated) || (!required && isAuthenticated); if (isRedirect) { if (props.staticContext) { props.staticContext.status = status; } return <Redirect from={route.path} to={redirect} status={status} />; } return <route.component {...props} route={route} />; }; checkAuth.propTypes = { staticContext: React.PropTypes.object, }; checkAuth.defaultProps = { staticContext: null, }; const RouteManager = (props, context) => ( <Switch> { props.routes.map((route) => ( <Route key={uuid.v4()} path={route.path} render={(props) => checkAuth(context.store, route, props)} exact={route.exact} strict={route.strict} /> )) } </Switch> ); RouteManager.propTypes = { routes: React.PropTypes.array.isRequired, }; RouteManager.contextTypes = { store: React.PropTypes.object, }; export default (routes) => { if (!routes) { return null; } return <RouteManager routes={routes} />; };
ajax/libs/rxjs/2.4.6/rx.lite.compat.js
maxklenk/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { var len = arr.length, a = new Array(len); for(var i = 0; i < len; i++) { a[i] = arr[i]; } return a; } Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return value && (type == 'function' || type == 'object') || false; }; function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Fix for Tessel if (!Object.prototype.propertyIsEnumerable) { Object.prototype.propertyIsEnumerable = function (key) { for (var k in this) { if (k === key) { return true; } } return false; }; } if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); } recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState([state, action], invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var taskId = 0, tasks = new Array(1000); var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); var onGlobalPostMessage = function (event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); tasks[handleId] = undefined; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (event) { var id = event.data, action = tasks[id]; action(); tasks[id] = undefined; }; scheduleMethod = function (action) { var id = taskId++; tasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler.default = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept(onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString() { return 'OnNext(' + this.value + ')'; } return function (value) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = Rx.Scheduler.currentThread); return new AnonymousObservable(function (observer) { var keys = Object.keys(obj), len = keys.length; return scheduler.scheduleRecursiveWithState(0, function (idx, self) { if (idx < len) { var key = keys[idx]; observer.onNext([key, obj[key]]); self(idx + 1); } else { observer.onCompleted(); } }); }); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** @deprecated use return or just */ Observable.returnValue = function () { //deprecate('returnValue', 'return or just'); return observableReturn.apply(null, arguments); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(error); }); }); }; /** @deprecated use #some instead */ Observable.throwException = function () { //deprecate('throwException', 'throwError'); return Observable.throwError.apply(null, arguments); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, this); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector(self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); /*try { var result = this.selector(x, this.i++, this.source); } catch (e) { return this.observer.onError(e); } this.observer.onNext(result);*/ }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate(x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return new AnonymousObservable(function (observer) { function handler() { var results = arguments; if (selector) { try { results = selector(results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var len = arguments.length, results = []; for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } if (selector) { try { results = selector(results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation) { event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch (event.type) { case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { // Handles jq, Angular.js, Zepto, Marionette, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param windowSize [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, windowSize, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, function (o) { return subject.subscribe(o); }); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count); self(count + 1, d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }, source); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, this); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }, source); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { o.onError(err); return; } try { res = resultSelector.apply(null, values); } catch (ex) { o.onError(ex); return; } o.onNext(res); } if (isDone && values[1]) { o.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(o) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { o.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { o.onNext(q.shift()); } o.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { __super__.call(this, subscribe, source); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue) { enableQueue == null && (enableQueue = true); __super__.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) this.subject.onCompleted(); else this.queue.push(Rx.Notification.createOnCompleted()); }, onError: function (error) { this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) this.subject.onError(error); else this.queue.push(Rx.Notification.createOnError(error)); }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(Rx.Notification.createOnNext(value)); } else { (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); hasRequested = true; } hasRequested && this.subject.onNext(value); }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while ((this.queue.length >= numberOfItems && numberOfItems > 0) || (this.queue.length > 0 && this.queue[0].kind !== 'N')) { var first = this.queue.shift(); first.accept(this.subject); if (first.kind === 'N') numberOfItems--; else { this.disposeCurrentRequest(); this.queue = []; } } return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0}; } //TODO I don't think this is ever necessary, since termination of a sequence without a queue occurs in the onCompletion or onError function //if (this.hasFailed) { // this.subject.onError(this.error); //} else if (this.hasCompleted) { // this.subject.onCompleted(); //} return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); var number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable; } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; } }); return ControlledSubject; }(Observable)); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }, source); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; } addProperties(BehaviorSubject.prototype, Observer, { /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { throw this.error; } return this.value; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { var maxSafeInteger = Math.pow(2, 53) - 1; function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
app/javascript/mastodon/features/ui/components/column.js
sylph-sin-tyaku/mastodon
import React from 'react'; import ColumnHeader from './column_header'; import PropTypes from 'prop-types'; import { debounce } from 'lodash'; import { scrollTop } from '../../../scroll'; import { isMobile } from '../../../is_mobile'; export default class Column extends React.PureComponent { static propTypes = { heading: PropTypes.string, icon: PropTypes.string, children: PropTypes.node, active: PropTypes.bool, hideHeadingOnMobile: PropTypes.bool, }; handleHeaderClick = () => { const scrollable = this.node.querySelector('.scrollable'); if (!scrollable) { return; } this._interruptScrollAnimation = scrollTop(scrollable); } scrollTop () { const scrollable = this.node.querySelector('.scrollable'); if (!scrollable) { return; } this._interruptScrollAnimation = scrollTop(scrollable); } handleScroll = debounce(() => { if (typeof this._interruptScrollAnimation !== 'undefined') { this._interruptScrollAnimation(); } }, 200) setRef = (c) => { this.node = c; } render () { const { heading, icon, children, active, hideHeadingOnMobile } = this.props; const showHeading = heading && (!hideHeadingOnMobile || (hideHeadingOnMobile && !isMobile(window.innerWidth))); const columnHeaderId = showHeading && heading.replace(/ /g, '-'); const header = showHeading && ( <ColumnHeader icon={icon} active={active} type={heading} onClick={this.handleHeaderClick} columnHeaderId={columnHeaderId} /> ); return ( <div ref={this.setRef} role='region' aria-labelledby={columnHeaderId} className='column' onScroll={this.handleScroll} > {header} {children} </div> ); } }
src/components/common/svg-icons/action/home.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHome = (props) => ( <SvgIcon {...props}> <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/> </SvgIcon> ); ActionHome = pure(ActionHome); ActionHome.displayName = 'ActionHome'; ActionHome.muiName = 'SvgIcon'; export default ActionHome;
app/javascript/mastodon/features/video/index.js
Chronister/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { fromJS } from 'immutable'; import { throttle } from 'lodash'; import classNames from 'classnames'; import { isFullscreen, requestFullscreen, exitFullscreen } from '../ui/util/fullscreen'; import { displayMedia } from '../../initial_state'; const messages = defineMessages({ play: { id: 'video.play', defaultMessage: 'Play' }, pause: { id: 'video.pause', defaultMessage: 'Pause' }, mute: { id: 'video.mute', defaultMessage: 'Mute sound' }, unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' }, hide: { id: 'video.hide', defaultMessage: 'Hide video' }, expand: { id: 'video.expand', defaultMessage: 'Expand video' }, close: { id: 'video.close', defaultMessage: 'Close video' }, fullscreen: { id: 'video.fullscreen', defaultMessage: 'Full screen' }, exit_fullscreen: { id: 'video.exit_fullscreen', defaultMessage: 'Exit full screen' }, }); const formatTime = secondsNum => { let hours = Math.floor(secondsNum / 3600); let minutes = Math.floor((secondsNum - (hours * 3600)) / 60); let seconds = secondsNum - (hours * 3600) - (minutes * 60); if (hours < 10) hours = '0' + hours; if (minutes < 10) minutes = '0' + minutes; if (seconds < 10) seconds = '0' + seconds; return (hours === '00' ? '' : `${hours}:`) + `${minutes}:${seconds}`; }; export const findElementPosition = el => { let box; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0, }; } const docEl = document.documentElement; const body = document.body; const clientLeft = docEl.clientLeft || body.clientLeft || 0; const scrollLeft = window.pageXOffset || body.scrollLeft; const left = (box.left + scrollLeft) - clientLeft; const clientTop = docEl.clientTop || body.clientTop || 0; const scrollTop = window.pageYOffset || body.scrollTop; const top = (box.top + scrollTop) - clientTop; return { left: Math.round(left), top: Math.round(top), }; }; export const getPointerPosition = (el, event) => { const position = {}; const box = findElementPosition(el); const boxW = el.offsetWidth; const boxH = el.offsetHeight; const boxY = box.top; const boxX = box.left; let pageY = event.pageY; let pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (pageY - boxY) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; }; export default @injectIntl class Video extends React.PureComponent { static propTypes = { preview: PropTypes.string, src: PropTypes.string.isRequired, alt: PropTypes.string, width: PropTypes.number, height: PropTypes.number, sensitive: PropTypes.bool, startTime: PropTypes.number, onOpenVideo: PropTypes.func, onCloseVideo: PropTypes.func, detailed: PropTypes.bool, inline: PropTypes.bool, intl: PropTypes.object.isRequired, }; state = { currentTime: 0, duration: 0, volume: 0.5, paused: true, dragging: false, containerWidth: false, fullscreen: false, hovered: false, muted: false, revealed: displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all', }; // hard coded in components.scss // any way to get ::before values programatically? volWidth = 50; volOffset = 70; volHandleOffset = v => { const offset = v * this.volWidth + this.volOffset; return (offset > 110) ? 110 : offset; } setPlayerRef = c => { this.player = c; if (c) { this.setState({ containerWidth: c.offsetWidth, }); } } setVideoRef = c => { this.video = c; } setSeekRef = c => { this.seek = c; } setVolumeRef = c => { this.volume = c; } handleClickRoot = e => e.stopPropagation(); handlePlay = () => { this.setState({ paused: false }); } handlePause = () => { this.setState({ paused: true }); } handleTimeUpdate = () => { this.setState({ currentTime: Math.floor(this.video.currentTime), duration: Math.floor(this.video.duration), }); } handleVolumeMouseDown = e => { document.addEventListener('mousemove', this.handleMouseVolSlide, true); document.addEventListener('mouseup', this.handleVolumeMouseUp, true); document.addEventListener('touchmove', this.handleMouseVolSlide, true); document.addEventListener('touchend', this.handleVolumeMouseUp, true); this.handleMouseVolSlide(e); e.preventDefault(); e.stopPropagation(); } handleVolumeMouseUp = () => { document.removeEventListener('mousemove', this.handleMouseVolSlide, true); document.removeEventListener('mouseup', this.handleVolumeMouseUp, true); document.removeEventListener('touchmove', this.handleMouseVolSlide, true); document.removeEventListener('touchend', this.handleVolumeMouseUp, true); } handleMouseVolSlide = throttle(e => { const rect = this.volume.getBoundingClientRect(); const x = (e.clientX - rect.left) / this.volWidth; //x position within the element. if(!isNaN(x)) { var slideamt = x; if(x > 1) { slideamt = 1; } else if(x < 0) { slideamt = 0; } this.video.volume = slideamt; this.setState({ volume: slideamt }); } }, 60); handleMouseDown = e => { document.addEventListener('mousemove', this.handleMouseMove, true); document.addEventListener('mouseup', this.handleMouseUp, true); document.addEventListener('touchmove', this.handleMouseMove, true); document.addEventListener('touchend', this.handleMouseUp, true); this.setState({ dragging: true }); this.video.pause(); this.handleMouseMove(e); e.preventDefault(); e.stopPropagation(); } handleMouseUp = () => { document.removeEventListener('mousemove', this.handleMouseMove, true); document.removeEventListener('mouseup', this.handleMouseUp, true); document.removeEventListener('touchmove', this.handleMouseMove, true); document.removeEventListener('touchend', this.handleMouseUp, true); this.setState({ dragging: false }); this.video.play(); } handleMouseMove = throttle(e => { const { x } = getPointerPosition(this.seek, e); const currentTime = Math.floor(this.video.duration * x); if (!isNaN(currentTime)) { this.video.currentTime = currentTime; this.setState({ currentTime }); } }, 60); togglePlay = () => { if (this.state.paused) { this.video.play(); } else { this.video.pause(); } } toggleFullscreen = () => { if (isFullscreen()) { exitFullscreen(); } else { requestFullscreen(this.player); } } componentDidMount () { document.addEventListener('fullscreenchange', this.handleFullscreenChange, true); document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange, true); document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true); document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true); } componentWillUnmount () { document.removeEventListener('fullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange, true); } handleFullscreenChange = () => { this.setState({ fullscreen: isFullscreen() }); } handleMouseEnter = () => { this.setState({ hovered: true }); } handleMouseLeave = () => { this.setState({ hovered: false }); } toggleMute = () => { this.video.muted = !this.video.muted; this.setState({ muted: this.video.muted }); } toggleReveal = () => { if (this.state.revealed) { this.video.pause(); } this.setState({ revealed: !this.state.revealed }); } handleLoadedData = () => { if (this.props.startTime) { this.video.currentTime = this.props.startTime; this.video.play(); } } handleProgress = () => { if (this.video.buffered.length > 0) { this.setState({ buffer: this.video.buffered.end(0) / this.video.duration * 100 }); } } handleOpenVideo = () => { const { src, preview, width, height, alt } = this.props; const media = fromJS({ type: 'video', url: src, preview_url: preview, description: alt, width, height, }); this.video.pause(); this.props.onOpenVideo(media, this.video.currentTime); } handleCloseVideo = () => { this.video.pause(); this.props.onCloseVideo(); } render () { const { preview, src, inline, startTime, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive } = this.props; const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state; const progress = (currentTime / duration) * 100; const volumeWidth = (muted) ? 0 : volume * this.volWidth; const volumeHandleLoc = (muted) ? this.volHandleOffset(0) : this.volHandleOffset(volume); const playerStyle = {}; let { width, height } = this.props; if (inline && containerWidth) { width = containerWidth; height = containerWidth / (16/9); playerStyle.width = width; playerStyle.height = height; } let preload; if (startTime || fullscreen || dragging) { preload = 'auto'; } else if (detailed) { preload = 'metadata'; } else { preload = 'none'; } let warning; if (sensitive) { warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />; } else { warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />; } return ( <div role='menuitem' className={classNames('video-player', { inactive: !revealed, detailed, inline: inline && !fullscreen, fullscreen })} style={playerStyle} ref={this.setPlayerRef} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} onClick={this.handleClickRoot} tabIndex={0} > <video ref={this.setVideoRef} src={src} poster={preview} preload={preload} loop role='button' tabIndex='0' aria-label={alt} title={alt} width={width} height={height} volume={volume} onClick={this.togglePlay} onPlay={this.handlePlay} onPause={this.handlePause} onTimeUpdate={this.handleTimeUpdate} onLoadedData={this.handleLoadedData} onProgress={this.handleProgress} /> <button type='button' className={classNames('video-player__spoiler', { active: !revealed })} onClick={this.toggleReveal}> <span className='video-player__spoiler__title'>{warning}</span> <span className='video-player__spoiler__subtitle'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span> </button> <div className={classNames('video-player__controls', { active: paused || hovered })}> <div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}> <div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} /> <div className='video-player__seek__progress' style={{ width: `${progress}%` }} /> <span className={classNames('video-player__seek__handle', { active: dragging })} tabIndex='0' style={{ left: `${progress}%` }} /> </div> <div className='video-player__buttons-bar'> <div className='video-player__buttons left'> <button type='button' aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} onClick={this.togglePlay}><i className={classNames('fa fa-fw', { 'fa-play': paused, 'fa-pause': !paused })} /></button> <button type='button' aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} onMouseEnter={this.volumeSlider} onMouseLeave={this.volumeSlider} onClick={this.toggleMute}><i className={classNames('fa fa-fw', { 'fa-volume-off': muted, 'fa-volume-up': !muted })} /></button> <div className='video-player__volume' onMouseDown={this.handleVolumeMouseDown} ref={this.setVolumeRef}> <div className='video-player__volume__current' style={{ width: `${volumeWidth}px` }} /> <span className={classNames('video-player__volume__handle')} tabIndex='0' style={{ left: `${volumeHandleLoc}px` }} /> </div> {(detailed || fullscreen) && <span> <span className='video-player__time-current'>{formatTime(currentTime)}</span> <span className='video-player__time-sep'>/</span> <span className='video-player__time-total'>{formatTime(duration)}</span> </span> } </div> <div className='video-player__buttons right'> {!onCloseVideo && <button type='button' aria-label={intl.formatMessage(messages.hide)} onClick={this.toggleReveal}><i className='fa fa-fw fa-eye' /></button>} {(!fullscreen && onOpenVideo) && <button type='button' aria-label={intl.formatMessage(messages.expand)} onClick={this.handleOpenVideo}><i className='fa fa-fw fa-expand' /></button>} {onCloseVideo && <button type='button' aria-label={intl.formatMessage(messages.close)} onClick={this.handleCloseVideo}><i className='fa fa-fw fa-compress' /></button>} <button type='button' aria-label={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} onClick={this.toggleFullscreen}><i className={classNames('fa fa-fw', { 'fa-arrows-alt': !fullscreen, 'fa-compress': fullscreen })} /></button> </div> </div> </div> </div> ); } }
react-sass-webpack/src/index.js
mypixel/web-starters
import React from 'react'; // just one method 'render' from react-dom rather than whole thing import { render } from 'react-dom'; import { BrowserRouter, Match, Miss } from 'react-router'; // styles import './styles/css/styles.css'; // components import App from './components/App'; import About from './components/About'; import NotFound from './components/NotFound'; // other import registerServiceWorker from './registerServiceWorker'; // using react router to handle URLs / rewriting const Root = () => { return ( <BrowserRouter> <div> <Match exactly pattern="/" component={App} /> <Match exactly pattern="/About" component={About} /> <Miss component={NotFound} /> </div> </BrowserRouter> ) } render(<Root/>, document.querySelector('#app')); registerServiceWorker();
Realization/frontend/czechidm-acc/src/content/rolecatalogue/RoleCatalogueAccounts.js
bcvsolutions/CzechIdMng
import PropTypes from 'prop-types'; import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import _ from 'lodash'; // import { Basic, Advanced, Domain, Managers, Utils } from 'czechidm-core'; import { RoleCatalogueAccountManager, AccountManager } from '../../redux'; import AccountTypeEnum from '../../domain/AccountTypeEnum'; import SystemEntityTypeEnum from '../../domain/SystemEntityTypeEnum'; const uiKey = 'role-catalogue-accounts-table'; const manager = new RoleCatalogueAccountManager(); const accountManager = new AccountManager(); const roleCatalogueManager = new Managers.RoleCatalogueManager(); /** * Role catalogue accounts * * @author Kučera */ class RoleCatalogueAccounts extends Advanced.AbstractTableContent { constructor(props, context) { super(props, context); } getManager() { return manager; } getUiKey() { return uiKey; } getContentKey() { return 'acc:content.roleCatalogue.accounts'; } getNavigationKey() { return 'role-catalogue-accounts'; } showDetail(entity) { if (!Utils.Entity.isNew(entity)) { this.context.store.dispatch(this.getManager().fetchPermissions(entity.id, `${this.getUiKey()}-detail`)); } // const entityFormData = _.merge({}, entity, { identity: entity._embedded && entity._embedded.identity ? entity._embedded.identity.id : this.props.match.params.entityId, account: entity.account ? entity.account.id : null }); // super.showDetail(entityFormData, () => { this.refs.account.focus(); }); } save(entity, event) { const formEntity = this.refs.form.getData(); const state = this.context.store.getState(); if (Utils.Entity.isNew(formEntity)) { const roleCatalogue = Utils.Entity.getEntity(state, roleCatalogueManager.getEntityType(), formEntity.identity); formEntity.roleCatalogue = roleCatalogue.id; formEntity.account = formEntity.account; } // super.save(formEntity, event); } afterSave(entity, error) { if (!error) { this.addMessage({ message: this.i18n('save.success', { name: entity.account.uid }) }); } // super.afterSave(entity, error); } render() { const { entityId } = this.props.match.params; const { _showLoading, _permissions } = this.props; const { detail } = this.state; const forceSearchParameters = new Domain.SearchParameters().setFilter('roleCatalogueId', entityId); const accountSearchParameters = new Domain.SearchParameters().setFilter('entityType', SystemEntityTypeEnum.findKeyBySymbol(SystemEntityTypeEnum.ROLE_CATALOGUE)); return ( <div> <Helmet title={this.i18n('title')} /> <Basic.Confirm ref="confirm-delete" level="danger"/> <Basic.ContentHeader style={{ marginBottom: 0 }}> <span dangerouslySetInnerHTML={{ __html: this.i18n('header') }}/> </Basic.ContentHeader> <Basic.Panel className="no-border last"> <Advanced.Table ref="table" uiKey={uiKey} manager={this.getManager()} forceSearchParameters={forceSearchParameters} showRowSelection={Managers.SecurityManager.hasAnyAuthority(['ROLECATALOGUEACCOUNT_DELETE'])} rowClass={({rowIndex, data}) => { return (data[rowIndex]._embedded.account.inProtection) ? 'disabled' : ''; }} actions={ Managers.SecurityManager.hasAnyAuthority(['ROLECATALOGUEACCOUNT_DELETE']) ? [{ value: 'delete', niceLabel: this.i18n('action.delete.action'), action: this.onDelete.bind(this), disabled: false }] : null } buttons={ [ <Basic.Button level="success" key="add_button" className="btn-xs" onClick={this.showDetail.bind(this, { type: AccountTypeEnum.findKeyBySymbol(AccountTypeEnum.PERSONAL) })} rendered={Managers.SecurityManager.hasAnyAuthority(['ROLECATALOGUEACCOUNT_CREATE'])}> <Basic.Icon type="fa" icon="plus"/> {' '} {this.i18n('button.add')} </Basic.Button> ] }> <Advanced.Column property="" header="" className="detail-button" rendered={ Managers.SecurityManager.hasAuthority('ACCOUNT_READ') } cell={ ({ rowIndex, data }) => { return ( <Advanced.DetailButton title={this.i18n('button.detail')} rendered={Managers.SecurityManager.hasAnyAuthority(['ROLECATALOGUEACCOUNT_READ'])} onClick={this.showDetail.bind(this, data[rowIndex])}/> ); } }/> <Advanced.Column rendered={false} property="_embedded.account.accountType" width="75px" header={this.i18n('acc:entity.Account.accountType')} sort face="enum" enumClass={AccountTypeEnum} /> <Advanced.Column property="_embedded.account.uid" header={this.i18n('acc:entity.Account.uid')} sort sortProperty="account.uid" face="text" /> <Advanced.Column header={this.i18n('acc:entity.System.name')} cell={ /* eslint-disable react/no-multi-comp */ ({rowIndex, data}) => { return ( <Advanced.EntityInfo entityType="system" entityIdentifier={ data[rowIndex]._embedded.account._embedded.system.id } face="popover" /> ); } }/> <Advanced.Column property="ownership" width="75px" header={this.i18n('acc:entity.IdentityAccount.ownership')} sort face="bool" /> <Advanced.Column property="_embedded.account.inProtection" header={this.i18n('acc:entity.Account.inProtection')} face="boolean" /> <Advanced.Column property="_embedded.account.endOfProtection" header={this.i18n('acc:entity.Account.endOfProtection')} face="datetime" /> </Advanced.Table> </Basic.Panel> <Basic.Modal bsSize="large" show={detail.show} onHide={this.closeDetail.bind(this)} backdrop="static" keyboard={!_showLoading}> <form onSubmit={this.save.bind(this, {})}> <Basic.Modal.Header closeButton={!_showLoading} text={this.i18n('create.header')} rendered={Utils.Entity.isNew(detail.entity)}/> <Basic.Modal.Header closeButton={!_showLoading} text={this.i18n('edit.header', { name: detail.entity.name })} rendered={!Utils.Entity.isNew(detail.entity)}/> <Basic.Modal.Body> <Basic.AbstractForm ref="form" showLoading={_showLoading} readOnly={ !manager.canSave(detail.entity, _permissions) }> <Basic.SelectBox ref="account" manager={ accountManager } label={ this.i18n('acc:entity.Account._type') } readOnly={ !Utils.Entity.isNew(detail.entity) } forceSearchParameters={ accountSearchParameters } required/> <Basic.Checkbox ref="ownership" label={this.i18n('acc:entity.IdentityAccount.ownership')}/> </Basic.AbstractForm> </Basic.Modal.Body> <Basic.Modal.Footer> <Basic.Button level="link" onClick={this.closeDetail.bind(this)} showLoading={_showLoading}> {this.i18n('button.close')} </Basic.Button> <Basic.Button type="submit" level="success" showLoading={ _showLoading } showLoadingIcon showLoadingText={ this.i18n('button.saving') } rendered={ manager.canSave(detail.entity, _permissions) }> { this.i18n('button.save') } </Basic.Button> </Basic.Modal.Footer> </form> </Basic.Modal> </div> ); } } RoleCatalogueAccounts.propTypes = { _showLoading: PropTypes.bool, }; RoleCatalogueAccounts.defaultProps = { _showLoading: false, }; function select(state) { return { _showLoading: Utils.Ui.isShowLoading(state, `${uiKey}-detail`), _permissions: Utils.Permission.getPermissions(state, `${uiKey}-detail`) }; } export default connect(select)(RoleCatalogueAccounts);
app/components/TTWindSection/index.js
j921216063/chenya
import React from 'react'; import styled from 'styled-components'; import { FormattedMessage } from 'react-intl'; import Section1 from 'components/Section1'; import Container from 'components/Container'; import H1 from 'components/H1'; import Img from 'components/Img'; import Icon from './10kw.png'; import messages from './messages'; const Wrap = styled.div` display: flex; justify-content: center; flex-flow: row wrap; `; const ImageBox = styled.div` width:50%; flex:1; img { width: 80%; } /* Normal */ @media screen and (max-width: 1280px) { img { width: 90%; } } /* Mobile */ @media screen and (max-width: 736px) { img { width: 90%; } } /* Mobile (Portrait) */ @media screen and (max-width: 480px) { flex:1 100%; text-align: center; img { width: 90%; } } `; const RightContainer = styled.div` /* background: blue; */ width:50%; flex: 1; /* Mobile (Portrait) */ @media screen and (max-width: 480px) { flex: 1 100%; } `; const Title = ({ className, text }) => ( <div className={className}> <span>{text}</span> </div> ); Title.propTypes = { className: React.PropTypes.string, text: React.PropTypes.string, }; const StyledTitle = styled(Title) ` margin-bottom: 30px; span { box-sizing: border-box; min-width: 300px; width: 400px; background-color: #32A2AF; padding: 6px; display: inline-block; color: white; font-weight: bolder; font-size: 22px; border: 3px solid #1B9FE2; border-radius: 10px; } /* Normal */ @media screen and (max-width: 1000px) { span { min-width: 300px; width: 300px; } } /* Mobile */ @media screen and (max-width: 736px) { span { min-width: 300px; width: 100%; } } /* Mobile (Portrait) */ @media screen and (max-width: 480px) { /* span { min-width: 300px; width: 300px; } */ } `; const Info = styled.div` font-weight: bolder; padding-bottom: 30px; `; const ItemBox = styled.div` &:nth-child(even) { padding-left: 40%; } /* Normal */ @media screen and (max-width: 1280px) { padding-left: 30px; &:nth-child(even) { padding-left: 30px; } } /* Mobile */ @media screen and (max-width: 736px) { padding-left: 0; &:nth-child(even) { padding-left: 0; } } `; const TTWindSection = () => ( <Section1> <Container> <header> <H1> <FormattedMessage {...messages.header} /> </H1> </header> <Wrap> <ImageBox> <Img src={Icon} alt="" /> </ImageBox> <RightContainer> <ItemBox> <FormattedMessage {...messages.title1} > {(message) => (<StyledTitle text={message} />)} </FormattedMessage> <Info> <FormattedMessage {...messages.desc1} /> </Info> </ItemBox> <ItemBox> <FormattedMessage {...messages.title2} > {(message) => (<StyledTitle text={message} />)} </FormattedMessage> <Info> <FormattedMessage {...messages.desc2} /> </Info> </ItemBox> <ItemBox> <FormattedMessage {...messages.title3} > {(message) => (<StyledTitle text={message} />)} </FormattedMessage> <Info> <FormattedMessage {...messages.desc3} /> </Info> </ItemBox> <ItemBox> <FormattedMessage {...messages.title4} > {(message) => (<StyledTitle text={message} />)} </FormattedMessage> <Info> <FormattedMessage {...messages.desc4} values={{ br: <br /> }} /> </Info> </ItemBox> </RightContainer> </Wrap> {/* <Img src={temp}/> */} </Container> </Section1> ); export default TTWindSection;
ajax/libs/angular.js/1.0.0rc10/angular-scenario.js
nareshs435/cdnjs
/*! * jQuery JavaScript Library v1.7.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Wed Mar 21 12:46:34 2012 -0700 */ (function( window, undefined ) { 'use strict'; // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( 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 = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context ? context.ownerDocument || context : document ); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.7.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.add( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; 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; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // 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 ( length === i ) { 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 = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.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({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // 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, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // 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.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).off( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery.Callbacks( "once memory" ); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { if ( typeof data !== "string" || !data ) { return null; } var xml, tmp; try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array, i ) { var len; if ( array ) { if ( indexOf ) { return indexOf.call( array, elem, i ); } len = array.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && array[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.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 ) { if ( typeof context === "string" ) { var 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 var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, 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 || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); // String to Object flags format cache var flagsCache = {}; // Convert String-formatted flags into Object-formatted ones and store in cache function createFlags( flags ) { var object = flagsCache[ flags ] = {}, i, length; flags = flags.split( /\s+/ ); for ( i = 0, length = flags.length; i < length; i++ ) { object[ flags[i] ] = true; } return object; } /* * Create a callback list using the following parameters: * * flags: an optional list of space-separated flags that will change how * the callback list behaves * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible flags: * * 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( flags ) { // Convert flags from String-formatted to Object-formatted // (we check in cache first) flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; var // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = [], // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Add one or several callbacks to the list add = function( args ) { var i, length, elem, type, actual; for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { // Inspect recursively add( elem ); } else if ( type === "function" ) { // Add if not in unique mode and callback is not in if ( !flags.unique || !self.has( elem ) ) { list.push( elem ); } } } }, // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; fired = true; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; } } firing = false; if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { self.disable(); } else { list = []; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { var length = list.length; add( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { firingStart = length; fire( memory[ 0 ], memory[ 1 ] ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { var args = arguments, argIndex = 0, argLength = args.length; for ( ; argIndex < argLength ; argIndex++ ) { for ( var i = 0; i < list.length; i++ ) { if ( args[ argIndex ] === list[ i ] ) { // Handle firingIndex and firingLength if ( firing ) { if ( i <= firingLength ) { firingLength--; if ( i <= firingIndex ) { firingIndex--; } } } // Remove the element list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique ) { break; } } } } } return this; }, // Control if a given callback is in the list has: function( fn ) { if ( list ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { if ( fn === list[ i ] ) { return true; } } } return false; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory || memory === true ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { fire( context, args ); } } 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; }; var // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ Deferred: function( func ) { var doneList = jQuery.Callbacks( "once memory" ), failList = jQuery.Callbacks( "once memory" ), progressList = jQuery.Callbacks( "memory" ), state = "pending", lists = { resolve: doneList, reject: failList, notify: progressList }, promise = { done: doneList.add, fail: failList.add, progress: progressList.add, state: function() { return state; }, // Deprecated isResolved: doneList.fired, isRejected: failList.fired, then: function( doneCallbacks, failCallbacks, progressCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); return this; }, always: function() { deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); return this; }, pipe: function( fnDone, fnFail, fnProgress ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ], progress: [ fnProgress, "notify" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { obj = promise; } else { for ( var key in promise ) { obj[ key ] = promise[ key ]; } } return obj; } }, deferred = promise.promise({}), key; for ( key in lists ) { deferred[ key ] = lists[ key ].fire; deferred[ key + "With" ] = lists[ key ].fireWith; } // Handle state deferred.done( function() { state = "resolved"; }, failList.disable, progressList.lock ).fail( function() { state = "rejected"; }, doneList.disable, progressList.lock ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( firstParam ) { var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, pValues = new Array( length ), count = length, pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(), promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { deferred.resolveWith( deferred, args ); } }; } function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; deferred.notifyWith( promise, pValues ); }; } if ( length > 1 ) { for ( ; i < length; i++ ) { if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return promise; } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, tds, events, eventName, i, isSupported, div = document.createElement( "div" ), documentElement = document.documentElement; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form(#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, pixelMargin: true }; // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: 1, change: 1, focusin: 1 }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } fragment.removeChild( div ); // Null elements to avoid leaks in IE fragment = select = opt = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, paddingMarginBorderVisibility, paddingMarginBorder, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; paddingMarginBorder = "padding:0;margin:0;border:"; positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" + "<table " + style + "' cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( window.getComputedStyle ) { div.innerHTML = ""; marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.style.width = "2px"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.width = div.style.padding = "1px"; div.style.border = 0; div.style.overflow = "hidden"; div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div style='width:5px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); } div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; div.innerHTML = html; outer = div.firstChild; inner = outer.firstChild; td = outer.nextSibling.firstChild.firstChild; offsetSupport = { doesNotAddBorder: ( inner.offsetTop !== 5 ), doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) }; inner.style.position = "fixed"; inner.style.top = "20px"; // safari subtracts parent border width here which is 5px offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); inner.style.position = inner.style.top = ""; outer.style.overflow = "hidden"; outer.style.position = "relative"; offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); if ( window.getComputedStyle ) { div.style.marginTop = "1%"; support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; } if ( typeof container.style.zoom !== "undefined" ) { container.style.zoom = 1; } body.removeChild( container ); marginDiv = div = container = null; jQuery.extend( support, offsetSupport ); }); return support; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var privateCache, thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, isEvents = name === "events"; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = ++jQuery.uuid; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } privateCache = thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Users should not attempt to inspect the internal events object using jQuery.data, // it is undocumented and subject to change. But does anyone listen? No. if ( isEvents && !thisCache[ name ] ) { return privateCache.events; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, // Reference to internal data cache key internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ internalKey ] : internalKey; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split( " " ); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the cache and need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : jQuery.isNumeric( data ) ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { for ( var name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery._data( elem, deferDataKey ); if ( defer && ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery._data( elem, queueDataKey ) && !jQuery._data( elem, markDataKey ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.fire(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = ( type || "fx" ) + "mark"; jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); if ( count ) { jQuery._data( elem, key, count ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { var q; if ( elem ) { type = ( type || "fx" ) + "queue"; q = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), hooks = {}; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } jQuery._data( elem, type + ".run", hooks ); fn.call( elem, function() { jQuery.dequeue( elem, type ); }, hooks ); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue " + type + ".run", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); 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 ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ 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 = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, 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, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { count++; tmp.add( resolve ); } } resolve(); return defer.promise( object ); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, nodeHook, boolHook, fixSpecified; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { classNames = ( value || "" ).split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, 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; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.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 ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.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 ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, l, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.toLowerCase().split( rspace ); l = attrNames.length; for ( ; i < l; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // 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; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.nodeValue = value + "" ); } }; // Apply the nodeHook to tabindex jQuery.attrHooks.tabindex.set = nodeHook.set; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = "" + value ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, rhoverHack = /(?:^|\s)hover(\.\S+)?\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, quickParse = function( selector ) { var quick = rquickIs.exec( selector ); if ( quick ) { // 0 1 2 3 // [ _, tag, id, class ] quick[1] = ( quick[1] || "" ).toLowerCase(); quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); } return quick; }, quickIs = function( elem, m ) { var attrs = elem.attributes || {}; return ( (!m[1] || elem.nodeName.toLowerCase() === m[1]) && (!m[2] || (attrs.id || {}).value === m[2]) && (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) ); }, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, quick, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { 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; } // 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 events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = 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" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // 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: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, quick: selector && quickParse( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + 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; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), t, tns, type, origType, namespaces, origCount, j, events, special, handle, eventType, handleObj; if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // 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; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.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 ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { handle = elemData.handle; if ( handle ) { handle.elem = null; } // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, [ "events", "handle" ], true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var type = event.type || event, namespaces = [], cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; // 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( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // 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 ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( 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) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; old = null; for ( ; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old && old === elem.ownerDocument ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === 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( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { 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 ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments, 0 ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = [], i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; 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 that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this.ownerDocument || this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process events on disabled elements (#6911, #8165) if ( cur.disabled !== true ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = ( handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) ); } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( 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; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) if ( event.metaKey === undefined ) { event.metaKey = event.ctrlKey; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + 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.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // 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; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector, ret; // For mousenter/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; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !form._submit_attached ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); form._submit_attached = true; } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; jQuery.event.simulate( "change", this, event, true ); } }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); elem._change_attached = true; } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } 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 this; } 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 this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var 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 ( var 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 ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, 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 ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache" + (Math.random() + '').replace('.', ''), done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set, seed ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { filter = Expr.filter[ type ]; left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); pass = not ^ found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Utility function for retreiving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, 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; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var first, last, doneName, parent, cache, count, diff, type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Sizzle.attr ? Sizzle.attr( elem, name ) : Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : !type && Sizzle.attr ? result != null : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } // Expose origPOS // "global" as in regardless of relation to brackets/parens Expr.match.globalPOS = origPOS; var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } 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 : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context, seed ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; Sizzle.selectors.attrMap = {}; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.globalPOS, // 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({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". POS.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array (deprecated as of jQuery 1.7) if ( jQuery.isArray( selectors ) ) { var level = 1; while ( cur && cur.ownerDocument && cur !== context ) { for ( i = 0; i < selectors.length; i++ ) { if ( jQuery( cur ).is( selectors[ i ] ) ) { ret.push({ selector: selectors[ i ], elem: cur, level: level }); } } cur = cur.parentNode; level++; } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var 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.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } 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() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery.clean( arguments ); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery.clean(arguments) ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } 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 jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : null; } if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); 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( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || ( l > 1 && i < lastIndex ) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { jQuery.ajax({ type: "GET", global: false, url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); // Clear flags for bubbling special change/submit events, they must // be reattached when the newly cloned events are first activated dest.removeAttribute( "_submit_attached" ); dest.removeAttribute( "_change_attached" ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc, first = args[ 0 ]; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { cacheable = true; cacheresults = jQuery.fragments[ first ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ first ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "input" ) { fixDefaultChecked( elem ); // Skip scripts, get other children } else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } // Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js function shimCloneNode( elem ) { var div = document.createElement( "div" ); safeFragment.appendChild( div ); div.innerHTML = elem.outerHTML; return div.firstChild; } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, // IE<=8 does not properly clone detached, unknown element nodes clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ? elem.cloneNode( true ) : shimCloneNode( elem ); if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType, script, j, ret = []; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"), safeChildNodes = safeFragment.childNodes, remove; // Append wrapper element to unknown element safe doc fragment if ( context === document ) { // Use the fragment we've already created for this document safeFragment.appendChild( div ); } else { // Use a fragment created with the owner document createSafeFragment( context ).appendChild( div ); } // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Clear elements from DocumentFragment (safeFragment or otherwise) // to avoid hoarding elements. Fixes #11356 if ( div ) { div.parentNode.removeChild( div ); // Guard against -1 index exceptions in FF3.6 if ( safeChildNodes.length > 0 ) { remove = safeChildNodes[ safeChildNodes.length - 1 ]; if ( remove && remove.parentNode ) { remove.parentNode.removeChild( remove ); } } } } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { script = ret[i]; if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) { scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script ); } else { if ( script.nodeType === 1 ) { var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( script ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data && data.events ) { for ( var 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 ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnum = /^[\-+]?(?:\d*\.)?\d+$/i, rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i, rrelNum = /^([\-+])=([\-+.\de]+)/, rmargin = /^margin/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, // order is important! cssExpand = [ "Top", "Right", "Bottom", "Left" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }; 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; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": 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: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // 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, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } 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 ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}, ret, name; // 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.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // DEPRECATED in 1.3, Use jQuery.css() instead jQuery.curCSS = jQuery.css; if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle, width, style = elem.style; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } // A tribute to the "awesome hack by Dean Edwards" // WebKit uses "computed value (percentage if specified)" instead of "used value" for margins // which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) { width = style.width; style.width = ret; ret = computedStyle.width; style.width = width; } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, uncomputed, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && (uncomputed = style[ name ]) ) { ret = uncomputed; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( rnumnonpx.test( ret ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWidthOrHeight( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, i = name === "width" ? 1 : 0, len = 4; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i += 2 ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i += 2 ) { val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0; } } } return val + "px"; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWidthOrHeight( elem, name, extra ); } else { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } } }, set: function( elem, value ) { return rnum.test( value ) ? value + "px" : value; } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "margin-right" ); } else { return elem.style.marginRight; } }); } }; } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // 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, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* 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 = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // 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 = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // 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 ); } } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // 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 ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); 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; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // 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 ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // 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: { context: true, url: true } }, 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 // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { 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; var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { 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( "ajax" + ( isSuccess ? "Success" : "Error" ), [ 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" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // 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 ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // 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 If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // 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 || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // 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 ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.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 ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.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 { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // 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 function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for ( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for ( key in s.converters ) { if ( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if ( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for ( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.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 ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback ); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( (display === "" && jQuery.css(elem, "display") === "none") || !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data( elem, "olddisplay" ) || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { var elem, display, i = 0, j = this.length; for ( ; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = jQuery.css( elem, "display" ); if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed( speed, easing, callback ); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); function doAnimation() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, e, hooks, replace, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; // first pass over propertys to expand / normalize for ( p in prop ) { name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) { replace = hooks.expand( prop[ name ] ); delete prop[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'p' from above because we have the correct "name" for ( p in replace ) { if ( ! ( p in prop ) ) { prop[ p ] = replace[ p ]; } } } } for ( name in prop ) { val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) { this.style.display = "inline-block"; } else { this.style.zoom = 1; } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test( val ) ) { // Tracks whether to show or hide based on private // data attached to the element method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 ); if ( method ) { jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" ); e[ method ](); } else { e[ val ](); } } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ( (end || 1) / e.cur() ) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; } return optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var index, hadTimers = false, timers = jQuery.timers, data = jQuery._data( this ); // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } function stopQueue( elem, data, index ) { var hooks = data[ index ]; jQuery.removeData( elem, index, true ); hooks.stop( gotoEnd ); } if ( type == null ) { for ( index in data ) { if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) { stopQueue( this, data, index ); } } } else if ( data[ index = type + ".run" ] && data[ index ].stop ){ stopQueue( this, data, index ); } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { if ( gotoEnd ) { // force the next step to be the last timers[ index ]( true ); } else { timers[ index ].saveState(); } hadTimers = true; 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 ( !( gotoEnd && hadTimers ) ) { jQuery.dequeue( this, type ); } }); } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx( "show", 1 ), slideUp: genFx( "hide", 1 ), slideToggle: genFx( "toggle", 1 ), 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.extend({ 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 }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ 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( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p ) { return p; }, swing: function( p ) { return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } ( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this ); }, // Get the current size cur: function() { if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = fxNow || createFxNow(); this.end = to; this.now = this.start = from; this.pos = this.state = 0; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); function t( gotoEnd ) { return self.step( gotoEnd ); } t.queue = this.options.queue; t.elem = this.elem; t.saveState = function() { if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { if ( self.options.hide ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } else if ( self.options.show ) { jQuery._data( self.elem, "fxshow" + self.prop, self.end ); } } }; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { var dataShow = jQuery._data( this.elem, "fxshow" + this.prop ); // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any flash of content if ( dataShow !== undefined ) { // This show is picking up where a previous hide or show left off this.custom( this.cur(), dataShow ); } else { this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() ); } // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom( this.cur(), 0 ); }, // Each step of an animation step: function( gotoEnd ) { var p, n, complete, t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( p in options.animatedProperties ) { if ( options.animatedProperties[ p ] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function( index, value ) { elem.style[ "overflow" + value ] = options.overflow[ index ]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery( elem ).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[ p ] ); jQuery.removeData( elem, "fxshow" + p, true ); // Toggle data is no longer needed jQuery.removeData( elem, "toggle" + p, true ); } } // Execute the complete function // in the event that the complete function throws an exception // we must ensure it won't be called twice. #5684 complete = options.complete; if ( complete ) { options.complete = false; complete.call( elem ); } } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ( (this.end - this.start) * this.pos ); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timer, timers = jQuery.timers, i = 0; for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = fx.now + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); // Ensure props that can't be negative don't go there on undershoot easing jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) { // exclude marginTop, marginLeft, marginBottom and marginRight from this list if ( prop.indexOf( "margin" ) ) { jQuery.fx.step[ prop ] = function( fx ) { jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit ); }; } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var getOffset, rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { getOffset = function( elem, doc, docElem, box ) { try { box = elem.getBoundingClientRect(); } catch(e) {} // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow( doc ), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { getOffset = function( elem, doc, docElem ) { var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var elem = this[0], doc = elem && elem.ownerDocument; if ( !doc ) { return null; } if ( elem === doc.body ) { return jQuery.offset.bodyOffset( elem ); } return getOffset( elem, doc, doc.documentElement ); }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // 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 ) ) { options = options.call( elem, i, 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({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { var clientProp = "client" + name, scrollProp = "scroll" + name, offsetProp = "offset" + name; // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : this[ type ]() : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : this[ type ]() : null; }; jQuery.fn[ type ] = function( value ) { return jQuery.access( this, function( elem, type, value ) { var doc, docElemProp, orig, ret; if ( jQuery.isWindow( elem ) ) { // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat doc = elem.document; docElemProp = doc.documentElement[ clientProp ]; return jQuery.support.boxModel && docElemProp || doc.body && doc.body[ clientProp ] || docElemProp; } // Get document width or height if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater doc = elem.documentElement; // when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height] // so we can't use max, as it'll choose the incorrect offset[Width/Height] // instead we use the correct client[Width/Height] // support:IE6 if ( doc[ clientProp ] >= doc[ scrollProp ] ) { return doc[ clientProp ]; } return Math.max( elem.body[ scrollProp ], doc[ scrollProp ], elem.body[ offsetProp ], doc[ offsetProp ] ); } // Get width or height on the element if ( value === undefined ) { orig = jQuery.css( elem, type ); ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; } // Set the width or height on the element jQuery( elem ).css( type, value ); }, type, value, arguments.length, null ); }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use 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. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window ); /** * @license AngularJS v1.0.0rc10 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, document){ var _jQuery = window.jQuery.noConflict(true); //////////////////////////////////// /** * @ngdoc function * @name angular.lowercase * @function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; /** * @ngdoc function * @name angular.uppercase * @function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);}) : s; }; var manualUppercase = function(s) { return isString(s) ? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);}) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) {return String.fromCharCode(code);} var Error = window.Error, /** holds major version number for IE or NaN for real browsers */ msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, toString = Object.prototype.toString, /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, /** @name angular.module.ng */ nodeName_, uid = ['0', '0', '0']; /** * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` * is the value of an object property or an array element and `key` is the object property key or * array element index. Specifying a `context` for the function is optional. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {Function} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isObject(obj) && isNumber(obj.length)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) { if (obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } } return obj; } function sortedKeys(obj) { var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys.sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } /** * when using forEach the params are value, key, but it is often useful to have key, value. * @param {function(string, *)} iteratorFn * @returns {function(*, string)} */ function reverseParams(iteratorFn) { return function(value, key) { iteratorFn(key, value) }; } /** * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } /** * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). */ function extend(dst) { forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function int(str) { return parseInt(str, 10); } function inherit(parent, extra) { return extend(new (extend(function() {}, {prototype:parent}))(), extra); } /** * @ngdoc function * @name angular.noop * @function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} noop.$inject = []; /** * @ngdoc function * @name angular.identity * @function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} identity.$inject = []; function valueFn(value) {return function() {return value;};} /** * @ngdoc function * @name angular.isUndefined * @function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){return typeof value == 'undefined';} /** * @ngdoc function * @name angular.isDefined * @function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){return typeof value != 'undefined';} /** * @ngdoc function * @name angular.isObject * @function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){return value != null && typeof value == 'object';} /** * @ngdoc function * @name angular.isString * @function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){return typeof value == 'string';} /** * @ngdoc function * @name angular.isNumber * @function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){return typeof value == 'number';} /** * @ngdoc function * @name angular.isDate * @function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return toString.apply(value) == '[object Date]'; } /** * @ngdoc function * @name angular.isArray * @function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return toString.apply(value) == '[object Array]'; } /** * @ngdoc function * @name angular.isFunction * @function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){return typeof value == 'function';} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isScope(obj) { return obj && obj.$evalAsync && obj.$watch; } function isFile(obj) { return toString.apply(obj) === '[object File]'; } function isBoolean(value) { return typeof value == 'boolean'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } /** * @ngdoc function * @name angular.isElement * @function * * @description * Determines if a reference is a DOM element (or wrapped jQuery element). * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). */ function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML') ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @description * Determines the number of elements in an array, the number of properties an object has, or * the length of a string. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Object} for more information about Angular arrays. * * @param {Object|Array|string} obj Object, array, or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { return indexOf(array, obj) != -1; } function indexOf(array, obj) { if (array.indexOf) return array.indexOf(obj); for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function arrayRemove(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.copy * @function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array, `source` is returned. * * Note: this function is used to augment the Object type in Angular expressions. See * {@link angular.module.ng.$filter} for more information about Angular arrays. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. */ function copy(source, destination){ if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope"); if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (source === destination) throw Error("Can't copy equivalent objects or arrays"); if (isArray(source)) { while(destination.length) { destination.pop(); } for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } /** * Create a shallow copy of an object */ function shallowCopy(src, dst) { dst = dst || {}; for(var key in src) { if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') { dst[key] = src[key]; } } return dst; } /** * @ngdoc function * @name angular.equals * @function * * @description * Determines if two objects or two values are equivalent. Supports value types, arrays and * objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties pass `===` comparison. * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) * * During a property comparision, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only be identify (`===`). * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { return isDate(o2) && o1.getTime() == o2.getTime(); } else { if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false; keySet = {}; for(key in o1) { if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false; } return true; } } } return false; } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /** * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are are prebound to the function. This feature is also * known as [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toJsonReplacer(key, value) { var val = value; if (/^\$+/.test(key)) { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; } else if (value && document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; } return val; } /** * @ngdoc function * @name angular.toJson * @function * * @description * Serializes input into a JSON-formatted string. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); } /** * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json) { return isString(json) ? JSON.parse(json) : json; } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { element = jqLite(element).clone(); try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. element.html(''); } catch(e) {} return jqLite('<div>').append(element).html().match(/^(<[^>]+>)/)[1]; } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = decodeURIComponent(key_value[0]); obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); }); return parts.length ? parts.join('&') : ''; } /** * We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace((pctEncodeSpaces ? null : /%20/g), '+'); } /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngApp * * @element ANY * @param {angular.Module} ngApp on optional application * {@link angular.module module} name to load. * * @description * * Use this directive to auto-bootstrap on application. Only * one directive can be used per HTML document. The directive * designates the root of the application and is typically placed * ot the root of the page. * * In the example below if the `ngApp` directive would not be placed * on the `html` element then the document would not be compiled * and the `{{ 1+2 }}` would not be resolved to `3`. * * `ngApp` is the easiest way to bootstrap an application. * <doc:example> <doc:source> I can add: 1 + 2 = {{ 1+2 }} </doc:source> </doc:example> * */ function angularInit(element, bootstrap) { var elements = [element], appElement, module, names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; function append(element) { element && elements.push(element); } forEach(names, function(name) { names[name] = true; append(document.getElementById(name)); name = name.replace(':', '\\:'); if (element.querySelectorAll) { forEach(element.querySelectorAll('.' + name), append); forEach(element.querySelectorAll('.' + name + '\\:'), append); forEach(element.querySelectorAll('[' + name + ']'), append); } }); forEach(elements, function(element) { if (!appElement) { var className = ' ' + element.className + ' '; var match = NG_APP_CLASS_REGEXP.exec(className); if (match) { appElement = element; module = (match[2] || '').replace(/\s+/g, ','); } else { forEach(element.attributes, function(attr) { if (!appElement && names[attr.name]) { appElement = element; module = attr.value; } }); } } }); if (appElement) { bootstrap(appElement, module ? [module] : []); } } /** * @ngdoc function * @name angular.bootstrap * @description * Use this function to manually start up angular application. * * See: {@link guide/dev_guide.bootstrap.manual_bootstrap Bootstrap} * * @param {Element} element DOM element which is the root of angular application. * @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules} * @returns {angular.module.auto.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules) { element = jqLite(element); modules = modules || []; modules.unshift('ng'); var injector = createInjector(modules); injector.invoke( ['$rootScope', '$compile', '$injector', function(scope, compile, injector){ scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); }] ); return injector; } var SNAKE_CASE_REGEXP = /[A-Z]/g; function snake_case(name, separator){ separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } function bindJQuery() { // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); JQLitePatchJQueryRemove('remove', true); JQLitePatchJQueryRemove('empty'); JQLitePatchJQueryRemove('html'); } else { jqLite = JQLite; } angular.element = jqLite; } /** * throw error of the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required")); } return arg; } function assertArgFn(arg, name, acceptArrayAnnotation) { if (acceptArrayAnnotation && isArray(arg)) { arg = arg[arg.length - 1]; } assertArg(isFunction(arg), name, 'not a function, got ' + (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** * @ngdoc interface * @name angular.Module * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } return ensure(ensure(window, 'angular', Object), 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @description * * The `angular.module` is a global place for creating and registering Angular modules. All * modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * * # Module * * A module is a collocation of services, directives, filters, and configure information. Module * is used to configure the {@link angular.module.AUTO.$injector $injector}. * * <pre> * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }); * </pre> * * Then you can create an injector and load your modules like this: * * <pre> * var injector = angular.injector(['ng', 'MyModule']) * </pre> * * However it's more likely that you'll just use * {@link angular.module.ng.$compileProvider.directive.ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the * the module is being retrieved for further configuration. * @param {Function} configFn Option configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw Error('No module: ' + name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke'); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @propertyOf angular.Module * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @propertyOf angular.Module * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @methodOf angular.Module * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the service. * @description * See {@link angular.module.AUTO.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @methodOf angular.Module * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link angular.module.AUTO.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @methodOf angular.Module * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link angular.module.AUTO.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @methodOf angular.Module * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link angular.module.AUTO.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @methodOf angular.Module * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link angular.module.AUTO.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#filter * @methodOf angular.Module * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link angular.module.ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @methodOf angular.Module * @param {string} name Controller name. * @param {Function} constructor Controller constructor function. * @description * See {@link angular.module.ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @methodOf angular.Module * @param {string} name directive name * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link angular.module.ng.$compileProvider.directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @methodOf angular.Module * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. */ config: config, /** * @ngdoc method * @name angular.Module#run * @methodOf angular.Module * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which needs to be performed when the injector with * with the current module is finished loading. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; } } }); }; }); } /** * @ngdoc property * @name angular.version * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '1.0.0rc10', // all of these placeholder strings will be replaced by rake's major: 1, // compile task minor: 0, dot: 0, codeName: 'tesseract-giftwrapping' }; function publishExternalAPI(angular){ extend(angular, { 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, 'callbacks': {counter: 0} }); angularModule = setupModuleLoader(window); try { angularModule('ngLocale'); } catch (e) { angularModule('ngLocale', []).provider('$locale', $LocaleProvider); } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, input: inputDirective, textarea: inputDirective, form: formDirective, script: scriptDirective, select: selectDirective, style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, ngCsp: ngCspDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngSubmit: ngSubmitDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, ngView: ngViewDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, required: requiredDirective, ngRequired: requiredDirective, ngValue: ngValueDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $defer: $DeferProvider, $document: $DocumentProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $route: $RouteProvider, $routeParams: $RouteParamsProvider, $rootScope: $RootScopeProvider, $q: $QProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $timeout: $TimeoutProvider, $window: $WindowProvider }); } ]); } ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite * implementation (commonly referred to as jqLite). * * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` * event fired. * * jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality * within a very small footprint, so only a subset of the jQuery API - methods, arguments and * invocation styles - are supported. * * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never * raw DOM references. * * ## Angular's jQuery lite provides the following methods: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) * - [children()](http://api.jquery.com/children/) * - [clone()](http://api.jquery.com/clone/) * - [contents()](http://api.jquery.com/contents/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [eq()](http://api.jquery.com/eq/) * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name. * - [hasClass()](http://api.jquery.com/hasClass/) * - [html()](http://api.jquery.com/html/) * - [next()](http://api.jquery.com/next/) * - [parent()](http://api.jquery.com/parent/) * - [prepend()](http://api.jquery.com/prepend/) * - [prop()](http://api.jquery.com/prop/) * - [ready()](http://api.jquery.com/ready/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [toggleClass()](http://api.jquery.com/toggleClass/) * - [unbind()](http://api.jquery.com/unbind/) * - [val()](http://api.jquery.com/val/) * - [wrap()](http://api.jquery.com/wrap/) * * ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite: * * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link api/angular.module.ng.$rootScope.Scope scope} of the current * element or its parent. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = JQLite.cache = {}, jqName = JQLite.expando = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; /** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } ///////////////////////////////////////////// // jQuery mutation patch // // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a // $destroy event on all DOM nodes being removed. // ///////////////////////////////////////////// function JQLitePatchJQueryRemove(name, dispatchThis) { var originalJqFn = jQuery.fn[name]; originalJqFn = originalJqFn.$original || originalJqFn; removePatch.$original = originalJqFn; jQuery.fn[name] = removePatch; function removePatch() { var list = [this], fireEvent = dispatchThis, set, setIndex, setLength, element, childIndex, childLength, children, fns, events; while(list.length) { set = list.shift(); for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { element = jqLite(set[setIndex]); if (fireEvent) { events = element.data('events'); if ( (fns = events && events.$destroy) ) { forEach(fns, function(fn){ fn.handler(); }); } } else { fireEvent = !fireEvent; } for(childIndex = 0, childLength = (children = element.children()).length; childIndex < childLength; childIndex++) { list.push(jQuery(children[childIndex])); } } } return originalJqFn.apply(this, arguments); } } ///////////////////////////////////////////// function JQLite(element) { if (element instanceof JQLite) { return element; } if (!(this instanceof JQLite)) { if (isString(element) && element.charAt(0) != '<') { throw Error('selectors not implemented'); } return new JQLite(element); } if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&nbsp;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteUnbind(element, type, fn) { var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!handle) return; //no listeners registered if (isUndefined(type)) { forEach(events, function(eventHandler, type) { removeEventListenerFn(element, type, eventHandler); delete events[type]; }); } else { if (isUndefined(fn)) { removeEventListenerFn(element, type, events[type]); delete events[type]; } else { arrayRemove(events[type], fn); } } } function JQLiteRemoveData(element) { var expandoId = element[jqName], expandoStore = jqCache[expandoId]; if (expandoStore) { if (expandoStore.handle) { expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); JQLiteUnbind(element); } delete jqCache[expandoId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteExpandoStore(element, key, value) { var expandoId = element[jqName], expandoStore = jqCache[expandoId || -1]; if (isDefined(value)) { if (!expandoStore) { element[jqName] = expandoId = jqNextId(); expandoStore = jqCache[expandoId] = {}; } expandoStore[key] = value; } else { return expandoStore && expandoStore[key]; } } function JQLiteData(element, key, value) { var data = JQLiteExpandoStore(element, 'data'), isSetter = isDefined(value), keyDefined = !isSetter && isDefined(key), isSimpleGetter = keyDefined && !isObject(key); if (!data && !isSimpleGetter) { JQLiteExpandoStore(element, 'data', data = {}); } if (isSetter) { data[key] = value; } else { if (keyDefined) { if (isSimpleGetter) { // don't create data in this case. return data && data[key]; } else { extend(data, key); } } else { return data; } } } function JQLiteHasClass(element, selector) { return ((" " + element.className + " ").replace(/[\n\t]/g, " "). indexOf( " " + selector + " " ) > -1); } function JQLiteRemoveClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ") ); }); } } function JQLiteAddClass(element, selector) { if (selector) { forEach(selector.split(' '), function(cssClass) { if (!JQLiteHasClass(element, cssClass)) { element.className = trim(element.className + ' ' + trim(cssClass)); } }); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } function JQLiteController(element, name) { return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); } function JQLiteInheritedData(element, name, value) { element = jqLite(element); // if element is the document object work with the html element instead // this makes $(document).scope() possible if(element[0].nodeType == 9) { element = element.find('html'); } while (element.length) { if (value = element.data(name)) return value; element = element.parent(); } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. JQLite(window).bind('load', trigger); // fallback to window.onload for others }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form'.split(','), function(value) { BOOLEAN_ELEMENTS[uppercase(value)] = true; }); function isBooleanAttr(element, name) { return BOOLEAN_ELEMENTS[element.nodeName] && BOOLEAN_ATTR[name.toLowerCase()]; } forEach({ data: JQLiteData, inheritedData: JQLiteInheritedData, scope: function(element) { return JQLiteInheritedData(element, '$scope'); }, controller: JQLiteController , injector: function(element) { return JQLiteInheritedData(element, '$injector'); }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { var val; if (msie <= 8) { // this is some IE specific weirdness that jQuery 1.6.4 does not sure why val = element.currentStyle && element.currentStyle[name]; if (val === '') val = 'auto'; } val = val || element.style[name]; if (msie <= 8) { // jquery weirdness :-/ val = (val === '') ? undefined : val; } return val; } }, attr: function(element, name, value){ var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || (element.attributes.getNamedItem(name)|| noop).specified) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: extend((msie < 9) ? function(element, value) { if (element.nodeType == 1 /** Element */) { if (isUndefined(value)) return element.innerText; element.innerText = value; } else { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { if (fn === JQLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); } else { for (key in arg1) { fn(this[i], key, arg1[key]); } } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); function createEventHandler(element, events) { var eventHandler = function (event, type) { if (!event.preventDefault) { event.preventDefault = function() { event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } if (isUndefined(event.defaultPrevented)) { var prevent = event.preventDefault; event.preventDefault = function() { event.defaultPrevented = true; prevent.call(event); }; event.defaultPrevented = false; } event.isDefaultPrevented = function() { return event.defaultPrevented; }; forEach(events[type || event.type], function(fn) { try { fn.call(element, event); } catch (e) { // Not much to do here since jQuery ignores these anyway } }); // Remove monkey-patched methods (IE), // as they would cause memory leaks in IE8. if (msie <= 8) { // IE7/8 does not allow to delete property on native object event.preventDefault = null; event.stopPropagation = null; event.isDefaultPrevented = null; } else { // It shouldn't affect normal browsers (native methods are defined on prototype). delete event.preventDefault; delete event.stopPropagation; delete event.isDefaultPrevented; } }; eventHandler.elem = element; return eventHandler; } ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function bindFn(element, type, fn){ var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!events) JQLiteExpandoStore(element, 'events', events = {}); if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); forEach(type.split(' '), function(type){ var eventFns = events[type]; if (!eventFns) { if (type == 'mouseenter' || type == 'mouseleave') { var counter = 0; events.mouseenter = []; events.mouseleave = []; bindFn(element, 'mouseover', function(event) { counter++; if (counter == 1) { handle(event, 'mouseenter'); } }); bindFn(element, 'mouseout', function(event) { counter --; if (counter == 0) { handle(event, 'mouseleave'); } }); } else { addEventListenerFn(element, type, handle); events[type] = []; } eventFns = events[type] } eventFns.push(fn); }); }, unbind: JQLiteUnbind, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeName != '#text') children.push(element); }); return children; }, contents: function(element) { return element.childNodes; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1) element.appendChild(child); }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ if (index) { element.insertBefore(child, index); } else { element.appendChild(child); index = child; } }); } }, wrap: function(element, wrapNode) { wrapNode = jqLite(wrapNode)[0]; var parent = element.parentNode; if (parent) { parent.replaceChild(wrapNode, element); } wrapNode.appendChild(element); }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { return element.nextSibling; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj) { var objType = typeof obj, key; if (objType == 'object' && obj !== null) { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { key = obj.$$hashKey = nextUid(); } } else { key = obj; } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(array){ forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key)] = value; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key)]; delete this[key]; return value; } }; /** * A map where multiple values can be added to the same key such that they form a queue. * @returns {HashQueueMap} */ function HashQueueMap() {} HashQueueMap.prototype = { /** * Same as array push, but using an array as the value for the hash */ push: function(key, value) { var array = this[key = hashKey(key)]; if (!array) { this[key] = [value]; } else { array.push(value); } }, /** * Same as array shift, but using an array as the value for the hash */ shift: function(key) { var array = this[key = hashKey(key)]; if (array) { if (array.length == 1) { delete this[key]; return array[0]; } else { return array.shift(); } } } }; /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/dev_guide.di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @returns {function()} Injector function. See {@link angular.module.AUTO.$injector $injector}. * * @example * Typical usage * <pre> * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick of your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document){ * $compile($document)($rootScope); * $rootScope.$digest(); * }); * </pre> */ /** * @ngdoc overview * @name angular.module.AUTO * @description * * Implicit module which gets automatically added to each {@link angular.module.AUTO.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(.+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function inferInjectionArgs(fn) { assertArgFn(fn); if (!fn.$inject) { var args = fn.$inject = []; var fnText = fn.toString().replace(STRIP_COMMENTS, ''); var argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, underscore, name){ args.push(name); }); }); } return fn.$inject; } /////////////////////////////////////// /** * @ngdoc object * @name angular.module.AUTO.$injector * @function * * @description * * `$injector` is used to retrieve object instances as defined by * {@link angular.module.AUTO.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * <pre> * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector){ * return $injector; * }).toBe($injector); * </pre> * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following ways are all valid way of annotating function with injection arguments and are equivalent. * * <pre> * // inferred (only works if code not minified/obfuscated) * $inject.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $inject.invoke(explicit); * * // inline * $inject.invoke(['serviceA', function(serviceA){}]); * </pre> * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be * parsed and the function arguments can be extracted. *NOTE:* This does not work with minfication, and obfuscation * tools since these tools change the argument names. * * ## `$inject` Annotation * By adding a `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name angular.module.AUTO.$injector#get * @methodOf angular.module.AUTO.$injector * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @return {*} The instance. */ /** * @ngdoc method * @name angular.module.AUTO.$injector#invoke * @methodOf angular.module.AUTO.$injector * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!function} fn The function to invoke. The function arguments come form the function annotation. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @return the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name angular.module.AUTO.$injector#instantiate * @methodOf angular.module.AUTO.$injector * @description * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies * all of the arguments to the constructor function as specified by the constructor annotation. * * @param {function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @return new instance of `Type`. */ /** * @ngdoc object * @name angular.module.AUTO.$provide * * @description * * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. * The providers share the same name as the instance they create with the `Provider` suffixed to them. * * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of * a service. The Provider can have additional methods which would allow for configuration of the provider. * * <pre> * function GreetProvider() { * var salutation = 'Hello'; * * this.salutation = function(text) { * salutation = text; * }; * * this.$get = function() { * return function (name) { * return salutation + ' ' + name + '!'; * }; * }; * } * * describe('Greeter', function(){ * * beforeEach(module(function($provide) { * $provide.provider('greet', GreetProvider); * }); * * it('should greet', inject(function(greet) { * expect(greet('angular')).toEqual('Hello angular!'); * })); * * it('should allow configuration of salutation', function() { * module(function(greetProvider) { * greetProvider.salutation('Ahoj'); * }); * inject(function(greet) { * expect(greet('angular')).toEqual('Ahoj angular!'); * }); * )}; * * }); * </pre> */ /** * @ngdoc method * @name angular.module.AUTO.$provide#provider * @methodOf angular.module.AUTO.$provide * @description * * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link angular.module.AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link angular.module.AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance */ /** * @ngdoc method * @name angular.module.AUTO.$provide#factory * @methodOf angular.module.AUTO.$provide * @description * * A short hand for configuring services if only `$get` method is required. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for * `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name angular.module.AUTO.$provide#service * @methodOf angular.module.AUTO.$provide * @description * * A short hand for registering service of given class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name angular.module.AUTO.$provide#value * @methodOf angular.module.AUTO.$provide * @description * * A short hand for configuring services if the `$get` method is a constant. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name angular.module.AUTO.$provide#constant * @methodOf angular.module.AUTO.$provide * @description * * A constant value, but unlike {@link angular.module.AUTO.$provide#value value} it can be injected * into configuration function (other modules) and it is not interceptable by * {@link angular.module.AUTO.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance */ /** * @ngdoc method * @name angular.module.AUTO.$provide#decorator * @methodOf angular.module.AUTO.$provide * @description * * Decoration of service, allows the decorator to intercept the service instance creation. The * returned instance may be the original instance, or a new instance which delegates to the * original instance. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instanciated. The function is called using the {@link angular.module.AUTO.$injector#invoke * injector.invoke} method and is therefore fully injectable. Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. */ function createInjector(modulesToLoad) { var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap(), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = createInternalInjector(providerCache, function() { throw Error("Unknown provider: " + path.join(' <- ')); }), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider); })); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } } } function provider(name, provider_) { if (isFunction(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw Error('Provider ' + name + ' must define $get factory method.'); } return providerCache[name + providerSuffix] = provider_; } function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, value) { return factory(name, valueFn(value)); } function constant(name, value) { providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad){ var runBlocks = []; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); if (isString(module)) { var moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); try { for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { var invokeArgs = invokeQueue[i], provider = invokeArgs[0] == '$injector' ? providerInjector : providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isFunction(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isArray(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + String(module[module.length - 1]); throw e; } } else { assertArgFn(module, 'module'); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName) { if (typeof serviceName !== 'string') { throw Error('Service name expected'); } if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw Error('Circular dependency: ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } finally { path.shift(); } } } function invoke(fn, self, locals){ var args = [], $inject, length, key; if (typeof fn == 'function') { $inject = inferInjectionArgs(fn); length = $inject.length; } else { if (isArray(fn)) { $inject = fn; length = $inject.length - 1; fn = $inject[length]; } assertArgFn(fn, 'fn'); } for(var i = 0; i < length; i++) { key = $inject[i]; args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key, path) ); } // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke switch (self ? -1 : args.length) { case 0: return fn(); case 1: return fn(args[0]); case 2: return fn(args[0], args[1]); case 3: return fn(args[0], args[1], args[2]); case 4: return fn(args[0], args[1], args[2], args[3]); case 5: return fn(args[0], args[1], args[2], args[3], args[4]); case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); default: return fn.apply(self, args); } } function instantiate(Type, locals) { var Constructor = function() {}, instance, returnedValue; Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; instance = new Constructor(); returnedValue = invoke(Type, instance, locals); return isObject(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService }; } } /** * @ngdoc function * @name angular.module.ng.$anchorScroll * @requires $window * @requires $location * @requires $rootScope * * @description * When called, it checks current value of `$location.hash()` and scroll to related element, * according to rules specified in * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. * * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; // helper function to get first anchor from a NodeList // can't use filter.filter, as it accepts only instances of Array // and IE can't convert NodeList to an array using [].slice // TODO(vojta): use filter if we change it to accept lists as well function getFirstAnchor(list) { var result = null; forEach(list, function(element) { if (!result && lowercase(element.nodeName) === 'a') result = element; }); return result; } function scroll() { var hash = $location.hash(), elm; // empty hash, scroll to the top of the page if (!hash) $window.scrollTo(0, 0); // element with given id else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); // first anchor with given name :-D else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); // no element and hash == 'top', scroll to the top of the page else if (hash === 'top') $window.scrollTo(0, 0); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $locaiton.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function() {return $location.hash();}, function() { $rootScope.$evalAsync(scroll); }); } return scroll; }]; } /** * @ngdoc object * @name angular.module.ng.$browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link angular.module.ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @ngdoc method * @name angular.module.ng.$browser#addPollFn * @methodOf angular.module.ng.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href, baseElement = document.find('base'); /** * @ngdoc method * @name angular.module.ng.$browser#url * @methodOf angular.module.ng.$browser * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link angular.module.ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { // setter if (url) { lastBrowserUrl = url; if ($sniffer.history) { if (replace) history.replaceState(null, '', url); else { history.pushState(null, '', url); // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 baseElement.attr('href', baseElement.attr('href')); } } else { if (replace) location.replace(url); else location.href = url; } return self; // getter } else { // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return location.href.replace(/%27/g,"'"); } }; var urlChangeListeners = [], urlChangeInit = false; function fireUrlChange() { if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); forEach(urlChangeListeners, function(listener) { listener(self.url()); }); } /** * @ngdoc method * @name angular.module.ng.$browser#onUrlChange * @methodOf angular.module.ng.$browser * @TODO(vojta): refactor to use node's syntax for events * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed by outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link angular.module.ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); // hashchange event if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * Returns current <base href> * (always relative - without domain) * * @returns {string=} */ self.baseHref = function() { var href = baseElement.attr('href'); return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; var cookiePath = self.baseHref(); /** * @ngdoc method * @name angular.module.ng.$browser#cookies * @methodOf angular.module.ng.$browser * * @param {string=} name Cookie name * @param {string=} value Cokkie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1; if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } if (lastCookies.length > 20) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " + "were already set (" + lastCookies.length + " > 20 )"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1)); } } } return lastCookies; } }; /** * @ngdoc method * @name angular.module.ng.$browser#defer * @methodOf angular.module.ng.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchroniously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * THIS DOC IS NOT VISIBLE because ngdocs can't process docs for foo#method.method * * @name angular.module.ng.$browser#defer.cancel * @methodOf angular.module.ng.$browser.defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; } function $BrowserProvider(){ this.$get = ['$window', '$log', '$sniffer', '$document', function( $window, $log, $sniffer, $document){ return new Browser($window, $document, $log, $sniffer); }]; } /** * @ngdoc object * @name angular.module.ng.$cacheFactory * * @description * Factory that constructs cache objects. * * * @param {string} cacheId Name or id of the newly created cache. * @param {object=} options Options object that specifies the cache behavior. Properties: * * - `{number=}` `capacity` — turns the cache into LRU cache. * * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. * - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache. * - `{{*}} `get({string} key) — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key) — Removes a key-value pair from the cache. * - `{void}` `removeAll() — Removes all cached values. * - `{void}` `destroy() — Removes references to this cache from $cacheFactory. * */ function $CacheFactoryProvider() { this.$get = function() { var caches = {}; function cacheFactory(cacheId, options) { if (cacheId in caches) { throw Error('cacheId ' + cacheId + ' taken'); } var size = 0, stats = extend({}, options, {id: cacheId}), data = {}, capacity = (options && options.capacity) || Number.MAX_VALUE, lruHash = {}, freshEnd = null, staleEnd = null; return caches[cacheId] = { put: function(key, value) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; if (size > capacity) { this.remove(staleEnd.key); } }, get: function(key) { var lruEntry = lruHash[key]; if (!lruEntry) return; refresh(lruEntry); return data[key]; }, remove: function(key) { var lruEntry = lruHash[key]; if (lruEntry == freshEnd) freshEnd = lruEntry.p; if (lruEntry == staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; delete data[key]; size--; }, removeAll: function() { data = {}; size = 0; lruHash = {}; freshEnd = staleEnd = null; }, destroy: function() { data = null; stats = null; lruHash = null; delete caches[cacheId]; }, info: function() { return extend({}, stats, {size: size}); } }; /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { if (entry != freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd == entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } } /** * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { if (nextEntry != prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } } } cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { info[cacheId] = cache.info(); }); return info; }; cacheFactory.get = function(cacheId) { return caches[cacheId]; }; return cacheFactory; }; } /** * @ngdoc object * @name angular.module.ng.$templateCache * * @description * Cache used for storing html templates. * * See {@link angular.module.ng.$cacheFactory $cacheFactory}. * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { return $cacheFactory('templates'); }]; } /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! * * DOM-related variables: * * - "node" - DOM Node * - "element" - DOM Element or Node * - "$node" or "$element" - jqLite-wrapped node or element * * * Compiler related stuff: * * - "linkFn" - linking fn of a single directive * - "nodeLinkFn" - function that aggregates all linking fns for a particular node * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) */ /** * @ngdoc function * @name angular.module.ng.$compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link angular.module.ng.$rootScope.Scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link angular.module.ng.$compileProvider.directive directives}. For each match it * executes corresponding template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link angular.module.ng.$compileProvider.directive.ngRepeat repeater} many-times, in which * case each call results in a view that is a DOM clone of the original template. * <doc:example module="compile"> <doc:source> <script> // declare a new module, and inject the $compileProvider angular.module('compile', [], function($compileProvider) { // configure new 'compile' directive by passing a directive // factory function. The factory function injects the '$compile' $compileProvider.directive('compile', function($compile) { // directive factory creates a link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'compile' expression for changes return scope.$eval(attrs.compile); }, function(value) { // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }) }); function Ctrl($scope) { $scope.name = 'Angular'; $scope.html = 'Hello {{name}}'; } </script> <div ng-controller="Ctrl"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div> </div> </doc:source> <doc:scenario> it('should auto compile', function() { expect(element('div[compile]').text()).toBe('Hello Angular'); input('html').enter('{{name}}!'); expect(element('div[compile]').text()).toBe('Angular!'); }); </doc:scenario> </doc:example> * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives. * @param {number} maxPriority only apply directives lower then given priority (Only effects the * root element(s), not their children) * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link angular.module.ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the linking function returns the element of the template. It is either the original element * passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var element = $compile('<p>{{total}}</p>')(scope); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var templateHTML = angular.element('<p>{{total}}</p>'), * scope = ....; * * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * For information on how the compiler works, see the * {@link guide/dev_guide.compiler Angular HTML Compiler} section of the Developer Guide. */ /** * @ngdoc service * @name angular.module.ng.$compileProvider * @function * * @description * */ $CompileProvider.$inject = ['$provide']; function $CompileProvider($provide) { var hasDirectives = {}, Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: '; /** * @ngdoc function * @name angular.module.ng.$compileProvider.directive * @methodOf angular.module.ng.$compileProvider * @function * * @description * Register directives with the compiler. * * @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as * <code>ng-bind</code>). * @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more * info. */ this.directive = function registerDirective(name, directiveFactory) { if (isString(name)) { assertArg(directiveFactory, 'directive'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; forEach(hasDirectives[name], function(directiveFactory) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { directive = { compile: valueFn(directive) }; } else if (!directive.compile && directive.link) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'A'; directives.push(directive); } catch (e) { $exceptionHandler(e); } }); return directives; }]); } hasDirectives[name].push(directiveFactory); } else { forEach(name, reverseParams(registerDirective)); } return this; }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', '$controller', function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, $controller) { var LOCAL_MODE = { attribute: function(localName, mode, parentScope, scope, attr) { scope[localName] = attr[localName]; }, evaluate: function(localName, mode, parentScope, scope, attr) { scope[localName] = parentScope.$eval(attr[localName]); }, bind: function(localName, mode, parentScope, scope, attr) { var getter = $interpolate(attr[localName]); scope.$watch( function() { return getter(parentScope); }, function(v) { scope[localName] = v; } ); }, accessor: function(localName, mode, parentScope, scope, attr) { var getter = noop, setter = noop, exp = attr[localName]; if (exp) { getter = $parse(exp); setter = getter.assign || function() { throw Error("Expression '" + exp + "' not assignable."); }; } scope[localName] = function(value) { return arguments.length ? setter(parentScope, value) : getter(parentScope); }; }, expression: function(localName, mode, parentScope, scope, attr) { scope[localName] = function(locals) { $parse(attr[localName])(parentScope, locals); }; } }; var Attributes = function(element, attr) { this.$$element = element; this.$$observers = {}; this.$attr = attr || {}; }; Attributes.prototype = { $normalize: directiveNormalize, /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. * @param {string} key Normalized key. (ie ngAttribute) * @param {string|boolean} value The value to set. If `null` attribute will be deleted. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. * Defaults to true. * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { var booleanKey = isBooleanAttr(this.$$element[0], key.toLowerCase()); if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); } else { this.$$element.attr(attrName, value); } } // fire observers forEach(this.$$observers[key], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); }, /** * Observe an interpolated attribute. * The observer will never be called, if given attribute is not interpolated. * * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(*)} fn Function that will be called whenever the attribute value changes. * @returns {function(*)} the `fn` Function passed in. */ $observe: function(key, fn) { // keep only observers for interpolated attrs if (this.$$observers[key]) { this.$$observers[key].push(fn); } return fn; } }; return compile; //================================ function compile($compileNode, transcludeFn, maxPriority) { if (!($compileNode instanceof jqLite)) { // jquery always rewraps, where as we need to preserve the original selector so that we can modify it. $compileNode = jqLite($compileNode); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in <span> forEach($compileNode, function(node, index){ if (node.nodeType == 3 /* text node */) { $compileNode[index] = jqLite(node).wrap('<span>').parent()[0]; } }); var compositeLinkFn = compileNodes($compileNode, transcludeFn, $compileNode, maxPriority); return function(scope, cloneConnectFn){ assertArg(scope, 'scope'); // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var $linkNode = cloneConnectFn ? JQLitePrototype.clone.call($compileNode) // IMPORTANT!!! : $compileNode; $linkNode.data('$scope', scope); safeAddClass($linkNode, 'ng-scope'); if (cloneConnectFn) cloneConnectFn($linkNode, scope); if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode); return $linkNode; }; } function wrongMode(localName, mode) { throw Error("Unsupported '" + mode + "' for '" + localName + "'."); } function safeAddClass($element, className) { try { $element.addClass(className); } catch(e) { // ignore, since it means that we are trying to set class on // SVG element, where class name is read-only. } } /** * Compile function matches each node in nodeList against the directives. Once all directives * for a particular node are collected their compile functions are executed. The compile * functions return values - the linking functions - are combined into a composite linking * function, which is the a linking function for the node. * * @param {NodeList} nodeList an array of nodes to compile * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the * rootElement must be set the jqLite collection of the compile root. This is * needed so that the jqLite collection items can be replaced with widgets. * @param {number=} max directive priority * @returns {?function} A composite linking function of all of the matched directives or null. */ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) { var linkFns = [], nodeLinkFn, childLinkFn, directives, attrs, linkFnFound; for(var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, maxPriority); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement) : null; childLinkFn = (nodeLinkFn && nodeLinkFn.terminal) ? null : compileNodes(nodeList[i].childNodes, nodeLinkFn ? nodeLinkFn.transclude : transcludeFn); linkFns.push(nodeLinkFn); linkFns.push(childLinkFn); linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn); } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) { var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn; for(var i = 0, n = 0, ii = linkFns.length; i < ii; n++) { node = nodeList[n]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(isObject(nodeLinkFn.scope)); jqLite(node).data('$scope', childScope); } else { childScope = scope; } childTranscludeFn = nodeLinkFn.transclude; if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) { nodeLinkFn(childLinkFn, childScope, node, $rootElement, (function(transcludeFn) { return function(cloneFn) { var transcludeScope = scope.$new(); return transcludeFn(transcludeScope, cloneFn). bind('$destroy', bind(transcludeScope, transcludeScope.$destroy)); }; })(childTranscludeFn || transcludeFn) ); } else { nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn); } } else if (childLinkFn) { childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn); } } } } /** * Looks for directives on the given node ands them to the directive collection which is sorted. * * @param node node to search * @param directives an array to which the directives are added to. This array is sorted before * the function returns. * @param attrs the shared attrs object which is used to populate the normalized attributes. * @param {number=} max directive priority */ function collectDirectives(node, directives, attrs, maxPriority) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, className; switch(nodeType) { case 1: /* Element */ // use the node name: <directive> addDirective(directives, directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority); // iterate over the attributes for (var attr, name, nName, value, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { attr = nAttrs[j]; if (attr.specified) { name = attr.name; nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; attrs[nName] = value = trim((msie && name == 'href') ? decodeURIComponent(node.getAttribute(name, 2)) : attr.value); if (isBooleanAttr(node, nName)) { attrs[nName] = true; // presence means true } addAttrInterpolateDirective(node, directives, value, nName); addDirective(directives, nName, 'A', maxPriority); } } // use class as directive className = node.className; if (isString(className)) { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); } } break; case 3: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; case 8: /* Comment */ try { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); if (addDirective(directives, nName, 'M', maxPriority)) { attrs[nName] = trim(match[2]); } } } catch (e) { // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; } directives.sort(byPriority); return directives; } /** * Once the directives have been collected their compile functions is executed. This method * is responsible for inlining directive templates as well as terminating the application * of the directives if the terminal directive has been reached.. * * @param {Array} directives Array of collected directives to execute their compile function. * this needs to be pre-sorted by priority order. * @param {Node} compileNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement} $rootElement If we are working on the root of the compile tree then this * argument has the root jqLite array so that we can replace widgets on it. * @returns linkFn */ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) { var terminalPriority = -Number.MAX_VALUE, preLinkFns = [], postLinkFns = [], newScopeDirective = null, newIsolatedScopeDirective = null, templateDirective = null, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, directiveName, $template, transcludeDirective, childTranscludeFn = transcludeFn, controllerDirectives, linkFn, directiveValue; // executes all directives on the current element for(var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; $template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives } if (directiveValue = directive.scope) { assertNoDuplicate('isolated scope', newIsolatedScopeDirective, directive, $compileNode); if (isObject(directiveValue)) { safeAddClass($compileNode, 'ng-isolate-scope'); newIsolatedScopeDirective = directive; } safeAddClass($compileNode, 'ng-scope'); newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; if (directiveValue = directive.controller) { controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } if (directiveValue = directive.transclude) { assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode); transcludeDirective = directive; terminalPriority = directive.priority; if (directiveValue == 'element') { $template = jqLite(compileNode); $compileNode = templateAttrs.$$element = jqLite('<!-- ' + directiveName + ': ' + templateAttrs[directiveName] + ' -->'); compileNode = $compileNode[0]; replaceWith($rootElement, jqLite($template[0]), compileNode); childTranscludeFn = compile($template, transcludeFn, terminalPriority); } else { $template = jqLite(JQLiteClone(compileNode)).contents(); $compileNode.html(''); // clear contents childTranscludeFn = compile($template, transcludeFn); } } if (directiveValue = directive.template) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; $template = jqLite('<div>' + trim(directiveValue) + '</div>').contents(); compileNode = $template[0]; if (directive.replace) { if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue); } replaceWith($rootElement, $compileNode, compileNode); var newTemplateAttrs = {$attr: {}}; // combine directives from the original node and from the template: // - take the array of directives for this element // - split it into two parts, those that were already applied and those that weren't // - collect directives from the template, add them to the second group and sort them // - append the second group with new directives to the first group directives = directives.concat( collectDirectives( compileNode, directives.splice(i + 1, directives.length - (i + 1)), newTemplateAttrs ) ); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; } else { $compileNode.html(directiveValue); } } if (directive.templateUrl) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), nodeLinkFn, $compileNode, templateAttrs, $rootElement, directive.replace, childTranscludeFn); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { addLinkFns(null, linkFn); } else if (linkFn) { addLinkFns(linkFn.pre, linkFn.post); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); } } if (directive.terminal) { nodeLinkFn.terminal = true; terminalPriority = Math.max(terminalPriority, directive.priority); } } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope; nodeLinkFn.transclude = transcludeDirective && childTranscludeFn; // might be normal or delayed nodeLinkFn depending on if templateUrl is present return nodeLinkFn; //////////////////// function addLinkFns(pre, post) { if (pre) { pre.require = directive.require; preLinkFns.push(pre); } if (post) { post.require = directive.require; postLinkFns.push(post); } } function getControllers(require, $element) { var value, retrievalMethod = 'data', optional = false; if (isString(require)) { while((value = require.charAt(0)) == '^' || value == '?') { require = require.substr(1); if (value == '^') { retrievalMethod = 'inheritedData'; } optional = optional || value == '?'; } value = $element[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { throw Error("No controller: " + require); } return value; } else if (isArray(require)) { value = []; forEach(require, function(require) { value.push(getControllers(require, $element)); }); } return value; } function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { var attrs, $element, i, ii, linkFn, controller; if (compileNode === linkNode) { attrs = templateAttrs; } else { attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); } $element = attrs.$$element; if (newScopeDirective && isObject(newScopeDirective.scope)) { forEach(newScopeDirective.scope, function(mode, name) { (LOCAL_MODE[mode] || wrongMode)(name, mode, scope.$parent || scope, scope, attrs); }); } if (controllerDirectives) { forEach(controllerDirectives, function(directive) { var locals = { $scope: scope, $element: $element, $attrs: attrs, $transclude: boundTranscludeFn }; forEach(directive.inject || {}, function(mode, name) { (LOCAL_MODE[mode] || wrongMode)(name, mode, newScopeDirective ? scope.$parent || scope : scope, locals, attrs); }); controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } $element.data( '$' + directive.name + 'Controller', $controller(controller, locals)); }); } // PRELINKING for(i = 0, ii = preLinkFns.length; i < ii; i++) { try { linkFn = preLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } // RECURSION childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING for(i = 0, ii = postLinkFns.length; i < ii; i++) { try { linkFn = postLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } } } /** * looks up the directive and decorates it with exception handling and proper parameters. We * call this the boundDirective. * * @param {string} name name of the directive to look up. * @param {string} location The directive must be found in specific format. * String containing any of theses characters: * * * `E`: element name * * `A': attribute * * `C`: class * * `M`: comment * @returns true if directive was added. */ function addDirective(tDirectives, name, location, maxPriority) { var match = false; if (hasDirectives.hasOwnProperty(name)) { for(var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i<ii; i++) { try { directive = directives[i]; if ( (maxPriority === undefined || maxPriority > directive.priority) && directive.restrict.indexOf(location) != -1) { tDirectives.push(directive); match = true; } } catch(e) { $exceptionHandler(e); } } } return match; } /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. * The desired effect is to have both of the attributes present. * * @param {object} dst destination attributes (original DOM) * @param {object} src source attributes (from the directive template) */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key]) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); } function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs, $rootElement, replace, childTranscludeFn) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { controller: null, templateUrl: null, transclude: null }); $compileNode.html(''); $http.get(origAsyncDirective.templateUrl, {cache: $templateCache}). success(function(content) { var compileNode, tempTemplateAttrs, $template; if (replace) { $template = jqLite('<div>' + trim(content) + '</div>').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content); } tempTemplateAttrs = {$attr: {}}; replaceWith($rootElement, $compileNode, compileNode); collectDirectives(compileNode, directives, tempTemplateAttrs); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { compileNode = beforeTemplateCompileNode; $compileNode.html(content); } directives.unshift(derivedSyncDirective); afterTemplateNodeLinkFn = applyDirectivesToNode(directives, $compileNode, tAttrs, childTranscludeFn); afterTemplateChildLinkFn = compileNodes($compileNode.contents(), childTranscludeFn); while(linkQueue.length) { var controller = linkQueue.pop(), linkRootElement = linkQueue.pop(), beforeTemplateLinkNode = linkQueue.pop(), scope = linkQueue.pop(), linkNode = compileNode; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { // it was cloned therefore we have to clone as well. linkNode = JQLiteClone(compileNode); replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); } afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller); }, scope, linkNode, $rootElement, controller); } linkQueue = null; }). error(function(response, code, headers, config) { throw Error('Failed to load template: ' + config.url); }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) { if (linkQueue) { linkQueue.push(scope); linkQueue.push(node); linkQueue.push(rootElement); linkQueue.push(controller); } else { afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller); }, scope, node, rootElement, controller); } }; } /** * Sorting function for bound directives. */ function byPriority(a, b) { return b.priority - a.priority; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { throw Error('Multiple directives [' + previousDirective.name + ', ' + directive.name + '] asking for ' + what + ' on: ' + startingTag(element)); } } function addTextInterpolateDirective(directives, text) { var interpolateFn = $interpolate(text, true); if (interpolateFn) { directives.push({ priority: 0, compile: valueFn(function(scope, node) { var parent = node.parent(), bindings = parent.data('$binding') || []; bindings.push(interpolateFn); safeAddClass(parent.data('$binding', bindings), 'ng-binding'); scope.$watch(interpolateFn, function(value) { node[0].nodeValue = value; }); }) }); } } function addAttrInterpolateDirective(node, directives, value, name) { var interpolateFn = $interpolate(value, true); // no interpolation found -> ignore if (!interpolateFn) return; directives.push({ priority: 100, compile: valueFn(function(scope, element, attr) { if (name === 'class') { // we need to interpolate classes again, in the case the element was replaced // and therefore the two class attrs got merged - we want to interpolate the result interpolateFn = $interpolate(attr[name], true); } // we define observers array only for interpolated attrs // and ignore observers for non interpolated attrs to save some memory attr.$$observers[name] = []; attr[name] = undefined; scope.$watch(interpolateFn, function(value) { attr.$set(name, value); }); }) }); } /** * This is a special jqLite.replaceWith, which can replace items which * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell, * but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ function replaceWith($rootElement, $element, newNode) { var oldNode = $element[0], parent = oldNode.parentNode, i, ii; if ($rootElement) { for(i = 0, ii = $rootElement.length; i < ii; i++) { if ($rootElement[i] == oldNode) { $rootElement[i] = newNode; break; } } } if (parent) { parent.replaceChild(newNode, oldNode); } newNode[jqLite.expando] = oldNode[jqLite.expando]; $element[0] = newNode; } }]; } var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': * my:DiRective * my-directive * x-my-directive * data-my:directive * * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function directiveNormalize(name) { return camelCase(name.replace(PREFIX_REGEXP, '')); } /** * Closure compiler type information */ function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, /* angular.Scope */ scope, /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} /** * @ngdoc object * @name angular.module.ng.$controllerProvider * @description * The {@link angular.module.ng.$controller $controller service} is used by Angular to create new * controllers. * * This provider allows controller registration via the * {@link angular.module.ng.$controllerProvider#register register} method. */ function $ControllerProvider() { var controllers = {}; /** * @ngdoc function * @name angular.module.ng.$controllerProvider#register * @methodOf angular.module.ng.$controllerProvider * @param {string} name Controller name * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { if (isObject(name)) { extend(controllers, name) } else { controllers[name] = constructor; } }; this.$get = ['$injector', '$window', function($injector, $window) { /** * @ngdoc function * @name angular.module.ng.$controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * check `window[constructor]` on the global `window` object * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. * * @description * `$controller` service is responsible for instantiating controllers. * * It's just simple call to {@link angular.module.AUTO.$injector $injector}, but extracted into * a service, so that one can override this service with {@link https://gist.github.com/1649788 * BC version}. */ return function(constructor, locals) { if(isString(constructor)) { var name = constructor; constructor = controllers.hasOwnProperty(name) ? controllers[name] : getter(locals.$scope, name, true) || getter($window, name, true); assertArgFn(constructor, name, true); } return $injector.instantiate(constructor, locals); }; }]; } /** * @ngdoc function * @name angular.module.ng.$defer * @deprecated Made obsolete by $timeout service. Please migrate your code. This service will be * removed with 1.0 final. * @requires $browser * * @description * Delegates to {@link angular.module.ng.$browser#defer $browser.defer}, but wraps the `fn` function * into a try/catch block and delegates any exceptions to * {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * * In tests you can use `$browser.defer.flush()` to flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$defer.cancel()`. */ /** * @ngdoc function * @name angular.module.ng.$defer#cancel * @methodOf angular.module.ng.$defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled. */ function $DeferProvider(){ this.$get = ['$rootScope', '$browser', '$log', function($rootScope, $browser, $log) { $log.warn('$defer service has been deprecated, migrate to $timeout'); function defer(fn, delay) { return $browser.defer(function() { $rootScope.$apply(fn); }, delay); } defer.cancel = function(deferId) { return $browser.defer.cancel(deferId); }; return defer; }]; } /** * @ngdoc object * @name angular.module.ng.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ function $DocumentProvider(){ this.$get = ['$window', function(window){ return jqLite(window.document); }]; } /** * @ngdoc function * @name angular.module.ng.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link angular.module.ngMock.$exceptionHandler mock $exceptionHandler} * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log){ return function(exception, cause) { $log.error.apply($log, arguments); }; }]; } /** * @ngdoc function * @name angular.module.ng.$interpolateProvider * @function * * @description * * Used for configuring the interpolation markup. Deafults to `{{` and `}}`. */ function $InterpolateProvider() { var startSymbol = '{{'; var endSymbol = '}}'; /** * @ngdoc method * @name angular.module.ng.$interpolateProvider#startSymbol * @methodOf angular.module.ng.$interpolateProvider * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. * * @prop {string=} value new value to set the starting symbol to. */ this.startSymbol = function(value){ if (value) { startSymbol = value; return this; } else { return startSymbol; } }; /** * @ngdoc method * @name angular.module.ng.$interpolateProvider#endSymbol * @methodOf angular.module.ng.$interpolateProvider * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * @prop {string=} value new value to set the ending symbol to. */ this.endSymbol = function(value){ if (value) { endSymbol = value; return this; } else { return startSymbol; } }; this.$get = ['$parse', function($parse) { var startSymbolLength = startSymbol.length, endSymbolLength = endSymbol.length; /** * @ngdoc function * @name angular.module.ng.$interpolate * @function * * @requires $parse * * @description * * Compiles a string with markup into an interpolation function. This service is used by the * HTML {@link angular.module.ng.$compile $compile} service for data binding. See * {@link angular.module.ng.$interpolateProvider $interpolateProvider} for configuring the * interpolation markup. * * <pre> var $interpolate = ...; // injected var exp = $interpolate('Hello {{name}}!'); expect(exp({name:'Angular'}).toEqual('Hello Angular!'); </pre> * * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. * @returns {function(context)} an interpolation function which is used to compute the interpolated * string. The function has these parameters: * * * `context`: an object against which any expressions embedded in the strings are evaluated * against. * */ return function(text, mustHaveExpression) { var startIndex, endIndex, index = 0, parts = [], length = text.length, hasInterpolation = false, fn, exp, concat = []; while(index < length) { if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { (index != startIndex) && parts.push(text.substring(index, startIndex)); parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); fn.exp = exp; index = endIndex + endSymbolLength; hasInterpolation = true; } else { // we did not find anything, so we have to add the remainder to the parts array (index != length) && parts.push(text.substring(index)); index = length; } } if (!(length = parts.length)) { // we added, nothing, must have been an empty string. parts.push(''); length = 1; } if (!mustHaveExpression || hasInterpolation) { concat.length = length; fn = function(context) { for(var i = 0, ii = length, part; i<ii; i++) { if (typeof (part = parts[i]) == 'function') { part = part(context); if (part == null || part == undefined) { part = ''; } else if (typeof part != 'string') { part = toJson(part); } } concat[i] = part; } return concat.join(''); }; fn.exp = text; fn.parts = parts; return fn; } }; }]; } var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = PATH_MATCH, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function matchUrl(url, obj) { var match = URL_MATCH.exec(url); match = { protocol: match[1], host: match[3], port: int(match[5]) || DEFAULT_PORTS[match[1]] || null, path: match[6] || '/', search: match[8], hash: match[10] }; if (obj) { obj.$$protocol = match.protocol; obj.$$host = match.host; obj.$$port = match.port; } return match; } function composeProtocolHostPort(protocol, host, port) { return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); } function pathPrefixFromBase(basePath) { return basePath.substr(0, basePath.lastIndexOf('/')); } function convertToHtml5Url(url, basePath, hashPrefix) { var match = matchUrl(url); // already html5 url if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) || match.hash.indexOf(hashPrefix) !== 0) { return url; // convert hashbang url -> html5 url } else { return composeProtocolHostPort(match.protocol, match.host, match.port) + pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length); } } function convertToHashbangUrl(url, basePath, hashPrefix) { var match = matchUrl(url); // already hashbang url if (decodeURIComponent(match.path) == basePath) { return url; // convert html5 url -> hashbang url } else { var search = match.search && '?' + match.search || '', hash = match.hash && '#' + match.hash || '', pathPrefix = pathPrefixFromBase(basePath), path = match.path.substr(pathPrefix.length); if (match.path.indexOf(pathPrefix) !== 0) { throw 'Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'; } return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath + '#' + hashPrefix + path + search + hash; } } /** * LocationUrl represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} url HTML5 url * @param {string} pathPrefix */ function LocationUrl(url, pathPrefix) { pathPrefix = pathPrefix || ''; /** * Parse given html5 (regular) url string into properties * @param {string} url HTML5 url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.path.indexOf(pathPrefix) !== 0) { throw 'Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !'; } this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length)); this.$$search = parseKeyValue(match.search); this.$$hash = match.hash && decodeURIComponent(match.hash) || ''; this.$$compose(); }; /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + pathPrefix + this.$$url; }; this.$$parse(url); } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is disabled or not supported * * @constructor * @param {string} url Legacy url * @param {string} hashPrefix Prefix for hash part (containing path and search) */ function LocationHashbangUrl(url, hashPrefix) { var basePath; /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { var match = matchUrl(url, this); if (match.hash && match.hash.indexOf(hashPrefix) !== 0) { throw 'Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !'; } basePath = match.path + (match.search ? '?' + match.search : ''); match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length)); if (match[1]) { this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]); } else { this.$$path = ''; } this.$$search = parseKeyValue(match[3]); this.$$hash = match[5] && decodeURIComponent(match[5]) || ''; this.$$compose(); }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) + basePath + (this.$$url ? '#' + hashPrefix + this.$$url : ''); }; this.$$parse(url); } LocationUrl.prototype = { /** * Has any change been replacing ? * @private */ $$replace: false, /** * @ngdoc method * @name angular.module.ng.$location#absUrl * @methodOf angular.module.ng.$location * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. * * @return {string} */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name angular.module.ng.$location#url * @methodOf angular.module.ng.$location * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} */ url: function(url, replace) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); if (match[1]) this.path(decodeURIComponent(match[1])); if (match[2] || match[1]) this.search(match[3] || ''); this.hash(match[5] || '', replace); return this; }, /** * @ngdoc method * @name angular.module.ng.$location#protocol * @methodOf angular.module.ng.$location * * @description * This method is getter only. * * Return protocol of current url. * * @return {string} */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name angular.module.ng.$location#host * @methodOf angular.module.ng.$location * * @description * This method is getter only. * * Return host of current url. * * @return {string} */ host: locationGetter('$$host'), /** * @ngdoc method * @name angular.module.ng.$location#port * @methodOf angular.module.ng.$location * * @description * This method is getter only. * * Return port of current url. * * @return {Number} */ port: locationGetter('$$port'), /** * @ngdoc method * @name angular.module.ng.$location#path * @methodOf angular.module.ng.$location * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * @param {string=} path New path * @return {string} */ path: locationGetterSetter('$$path', function(path) { return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name angular.module.ng.$location#search * @methodOf angular.module.ng.$location * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * @param {string|object<string,string>=} search New search params - string or hash object * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a * single search parameter. If the value is `null`, the parameter will be deleted. * * @return {string} */ search: function(search, paramValue) { if (isUndefined(search)) return this.$$search; if (isDefined(paramValue)) { if (paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = paramValue; } } else { this.$$search = isString(search) ? parseKeyValue(search) : search; } this.$$compose(); return this; }, /** * @ngdoc method * @name angular.module.ng.$location#hash * @methodOf angular.module.ng.$location * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * @param {string=} hash New hash fragment * @return {string} */ hash: locationGetterSetter('$$hash', identity), /** * @ngdoc method * @name angular.module.ng.$location#replace * @methodOf angular.module.ng.$location * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; LocationHashbangUrl.prototype = inherit(LocationUrl.prototype); function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc object * @name angular.module.ng.$location * * @requires $browser * @requires $sniffer * @requires $document * * @description * The $location service parses the URL in the browser address bar (based on the {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular Services: Using $location} */ /** * @ngdoc object * @name angular.module.ng.$locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ function $LocationProvider(){ var hashPrefix = '', html5Mode = false; /** * @ngdoc property * @name angular.module.ng.$locationProvider#hashPrefix * @methodOf angular.module.ng.$locationProvider * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.hashPrefix = function(prefix) { if (isDefined(prefix)) { hashPrefix = prefix; return this; } else { return hashPrefix; } }; /** * @ngdoc property * @name angular.module.ng.$locationProvider#html5Mode * @methodOf angular.module.ng.$locationProvider * @description * @param {string=} mode Use HTML5 strategy if available. * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { if (isDefined(mode)) { html5Mode = mode; return this; } else { return html5Mode; } }; this.$get = ['$rootScope', '$browser', '$sniffer', '$document', function( $rootScope, $browser, $sniffer, $document) { var currentUrl, basePath = $browser.baseHref() || '/', pathPrefix = pathPrefixFromBase(basePath), initUrl = $browser.url(); if (html5Mode) { if ($sniffer.history) { currentUrl = new LocationUrl(convertToHtml5Url(initUrl, basePath, hashPrefix), pathPrefix); } else { currentUrl = new LocationHashbangUrl(convertToHashbangUrl(initUrl, basePath, hashPrefix), hashPrefix); } // link rewriting var u = currentUrl, absUrlPrefix = composeProtocolHostPort(u.protocol(), u.host(), u.port()) + pathPrefix; $document.bind('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (event.ctrlKey || event.metaKey || event.which == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (elm.length && lowercase(elm[0].nodeName) !== 'a') { elm = elm.parent(); } var absHref = elm.prop('href'); if (!absHref || elm.attr('target') || absHref.indexOf(absUrlPrefix) !== 0) { // link to different domain or base path return; } // update location with href without the prefix currentUrl.url(absHref.substr(absUrlPrefix.length)); $rootScope.$apply(); event.preventDefault(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; }); } else { currentUrl = new LocationHashbangUrl(initUrl, hashPrefix); } // rewrite hashbang url <> html5 url if (currentUrl.absUrl() != initUrl) { $browser.url(currentUrl.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if (currentUrl.absUrl() != newUrl) { $rootScope.$evalAsync(function() { currentUrl.$$parse(newUrl); }); if (!$rootScope.$$phase) $rootScope.$digest(); } }); // update browser var changeCounter = 0; $rootScope.$watch(function $locationWatch() { if ($browser.url() != currentUrl.absUrl()) { changeCounter++; $rootScope.$evalAsync(function() { $browser.url(currentUrl.absUrl(), currentUrl.$$replace); currentUrl.$$replace = false; }); } return changeCounter; }); return currentUrl; }]; } /** * @ngdoc object * @name angular.module.ng.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <doc:example> <doc:source> <script> function LogCtrl($log) { this.$log = $log; this.message = 'Hello World!'; } </script> <div ng-controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ function $LogProvider(){ this.$get = ['$window', function($window){ return { /** * @ngdoc method * @name angular.module.ng.$log#log * @methodOf angular.module.ng.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name angular.module.ng.$log#warn * @methodOf angular.module.ng.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name angular.module.ng.$log#info * @methodOf angular.module.ng.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name angular.module.ng.$log#error * @methodOf angular.module.ng.$log * * @description * Write an error message */ error: consoleLog('error') }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop; if (logFn.apply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2); } } }]; } var OPERATORS = { 'null':function(){return null;}, 'true':function(){return true;}, 'false':function(){return false;}, undefined:noop, '+':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, '=':noop, '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);}, '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, // '|':function(self, locals, a,b){return a|b;}, '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, '!':function(self, locals, a){return !a(self, locals);} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, csp){ var tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), fn = OPERATORS[ch], fn2 = OPERATORS[ch2]; if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek() { return index + 1 < text.length ? text.charAt(index + 1) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function() {return number;}}); } function readIdent() { var ident = "", start = index, lastDot, peekIndex, methodName; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { if (ch == '.') lastDot = index; ident += ch; } else { break; } index++; } //check if this is not a method invocation and if it is back out to last dot if (lastDot) { peekIndex = index; while(peekIndex < text.length) { var ch = text.charAt(peekIndex); if (ch == '(') { methodName = ident.substr(lastDot - start + 1); ident = ident.substr(0, lastDot - start); index = peekIndex; break; } if(isWhitespace(ch)) { peekIndex++; } else { break; } } } var token = { index:start, text:ident }; if (OPERATORS.hasOwnProperty(ident)) { token.fn = token.json = OPERATORS[ident]; } else { var getter = getterFn(ident, csp); token.fn = extend(function(self, locals) { return (getter(self, locals)); }, { assign: function(self, value) { return setter(self, ident, value); } }); } tokens.push(token); if (methodName) { tokens.push({ index:lastDot, text: '.', json: false }); tokens.push({ index: lastDot + 1, text: methodName, json: false }); } } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({ index:start, text:rawString, string:string, json:true, fn:function() { return string; } }); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json, $filter, csp){ var ZERO = valueFn(0), value, tokens = lex(text, csp), assignment = _assignment, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = filterChain = function() { throwError("is not valid json", {text:text, index:0}); }; value = primary(); } else { value = statements(); } if (tokens.length !== 0) { throwError("is an unexpected token", tokens[0]); } return value; /////////////////////////////////// function throwError(msg, token) { throw Error("Syntax Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of the expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { throwError("is not valid json", token); } tokens.shift(); return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return function(self, locals) { return fn(self, locals, right); }; } function binaryFn(left, fn, right) { return function(self, locals) { return fn(self, locals, left, right); }; } function statements() { var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return statements.length == 1 ? statements[0] : function(self, locals){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self, locals); } return value; }; } } } function _filterChain() { var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter() { var token = expect(); var fn = $filter(token.text); var argsFn = []; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, locals, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } return fn.apply(self, args); }; return function() { return fnInvoke; }; } } } function expression() { return assignment(); } function _assignment() { var left = logicalOR(); var right; var token; if ((token = expect('='))) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = logicalOR(); return function(self, locals){ return left.assign(self, right(self, locals), locals); }; } else { return left; } } function logicalOR() { var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND() { var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality() { var left = relational(); var token; if ((token = expect('==','!='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational() { var left = additive(); var token; if ((token = expect('<', '>', '<=', '>='))) { left = binaryFn(left, token.fn, relational()); } return left; } function additive() { var left = multiplicative(); var token; while ((token = expect('+','-'))) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative() { var left = unary(); var token; while ((token = expect('*','/','%'))) { left = binaryFn(left, token.fn, unary()); } return left; } function unary() { var token; if (expect('+')) { return primary(); } else if ((token = expect('-'))) { return binaryFn(ZERO, token.fn, unary()); } else if ((token = expect('!'))) { return unaryFn(token.fn, unary()); } else { return primary(); } } function primary() { var primary; if (expect('(')) { primary = filterChain(); consume(')'); } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } } var next, context; while ((next = expect('(', '[', '.'))) { if (next.text === '(') { primary = functionCall(primary, context); context = null; } else if (next.text === '[') { context = primary; primary = objectIndex(primary); } else if (next.text === '.') { context = primary; primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field, csp); return extend( function(self, locals) { return getter(object(self, locals), locals); }, { assign:function(self, value, locals) { return setter(object(self, locals), field, value); } } ); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function(self, locals){ var o = obj(self, locals), i = indexFn(self, locals), v, p; if (!o) return undefined; v = o[i]; if (v && v.then) { p = v; if (!('$$v' in v)) { p.$$v = undefined; p.then(function(val) { p.$$v = val; }); } v = v.$$v; } return v; }, { assign:function(self, value, locals){ return obj(self, locals)[indexFn(self, locals)] = value; } }); } function _functionCall(fn, contextGetter) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function(self, locals){ var args = [], context = contextGetter ? contextGetter(self, locals) : self; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } var fnPtr = fn(self, locals) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(context, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; if (peekToken().text != ']') { do { elementFns.push(expression()); } while (expect(',')); } consume(']'); return function(self, locals){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self, locals)); } return array; }; } function object () { var keyValues = []; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); } while (expect(',')); } consume('}'); return function(self, locals){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self, locals); object[keyValue.key] = value; } return object; }; } } ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue) { var element = path.split('.'); for (var i = 0; element.length > 1; i++) { var key = element.shift(); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } obj[element.shift()] = setValue; return setValue; } /** * Return the value accesible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {string} path path to traverse * @param {boolean=true} bindFnToScope * @returns value as accesbile by path */ //TODO(misko): this function needs to be removed function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } var getterFnCache = {}; /** * Implementation of the "Black Hole" variant from: * - http://jsperf.com/angularjs-parse-getter/4 * - http://jsperf.com/path-evaluation-simplified/7 */ function cspSafeGetterFn(key0, key1, key2, key3, key4) { return function(scope, locals) { var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, promise; if (pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key0]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key1 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key1]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key2 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key2]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key3 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key3]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key4 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key4]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } return pathVal; }; }; function getterFn(path, csp) { if (getterFnCache.hasOwnProperty(path)) { return getterFnCache[path]; } var pathKeys = path.split('.'), pathKeysLength = pathKeys.length, fn; if (csp) { fn = (pathKeysLength < 6) ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4]) : function(scope, locals) { var i = 0, val do { val = cspSafeGetterFn( pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++] )(scope, locals); locals = undefined; // clear after first iteration scope = val; } while (i < pathKeysLength); return val; } } else { var code = 'var l, fn, p;\n'; forEach(pathKeys, function(key, index) { code += 'if(s === null || s === undefined) return s;\n' + 'l=s;\n' + 's='+ (index // we simply dereference 's' on any .dot notation ? 's' // but if we are first then we check locals first, and if so read it first : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + 'if (s && s.then) {\n' + ' if (!("$$v" in s)) {\n' + ' p=s;\n' + ' p.$$v = undefined;\n' + ' p.then(function(v) {p.$$v=v;});\n' + '}\n' + ' s=s.$$v\n' + '}\n'; }); code += 'return s;'; fn = Function('s', 'k', code); // s=scope, k=locals fn.toString = function() { return code; }; } return getterFnCache[path] = fn; } /////////////////////////////////// function $ParseProvider() { var cache = {}; this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { return function(exp) { switch(typeof exp) { case 'string': return cache.hasOwnProperty(exp) ? cache[exp] : cache[exp] = parser(exp, false, $filter, $sniffer.csp); case 'function': return exp; default: return noop; } }; }]; } /** * @ngdoc service * @name angular.module.ng.$q * @requires $rootScope * * @description * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is * performed asynchronously, and may or may not be finished at any given point in time. * * From the perspective of dealing with error handling, deferred and promise apis are to * asynchronous programing what `try`, `catch` and `throw` keywords are to synchronous programing. * * <pre> * // for the purpose of this example let's assume that variables `$q` and `scope` are * // available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { * // since this fn executes async in a future turn of the event loop, we need to wrap * // our code into an $apply call so that the model changes are properly observed. * scope.$apply(function() { * if (okToGreet(name)) { * deferred.resolve('Hello, ' + name + '!'); * } else { * deferred.reject('Greeting ' + name + ' is not allowed.'); * } * }); * }, 1000); * * return deferred.promise; * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * ); * </pre> * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff * comes in the way of * [guarantees that promise and deferred apis make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * * * # The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as apis * that can be used for signaling the successful or unsuccessful completion of the task. * * **Methods** * * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. * * **Properties** * * - promise – `{Promise}` – promise object associated with this deferred. * * * # The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. * * The purpose of the promise object is to allow for interested parties to get access to the result * of the deferred task when it completes. * * **Methods** * * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved * or rejected calls one of the success or error callbacks asynchronously as soon as the result * is available. The callbacks are called with a single argument the result or rejection reason. * * This method *returns a new promise* which is resolved or rejected via the return value of the * `successCallback` or `errorCallback`. * * * # Chaining promises * * Because calling `then` api of a promise returns a new derived promise, it is easily possible * to create a chain of promises: * * <pre> * promiseB = promiseA.then(function(result) { * return result + 1; * }); * * // promiseB will be resolved immediately after promiseA is resolved and it's value will be * // the result of promiseA incremented by 1 * </pre> * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of * the promises at any point in the chain. This makes it possible to implement powerful apis like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * * There are three main differences: * * - $q is integrated with the {@link angular.module.ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - $q promises are recognized by the templating engine in angular, which means that in templates * you can treat promises attached to a scope as if they were the resulting values. * - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. */ function $QProvider() { this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); }, $exceptionHandler); }]; } /** * Constructs a promise manager. * * @param {function(function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. */ function qFactory(nextTick, exceptionHandler) { /** * @ngdoc * @name angular.module.ng.$q#defer * @methodOf angular.module.ng.$q * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ var defer = function() { var pending = [], value, deferred; deferred = { resolve: function(val) { if (pending) { var callbacks = pending; pending = undefined; value = ref(val); if (callbacks.length) { nextTick(function() { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; value.then(callback[0], callback[1]); } }); } } }, reject: function(reason) { deferred.resolve(reject(reason)); }, promise: { then: function(callback, errback) { var result = defer(); var wrappedCallback = function(value) { try { result.resolve((callback || defaultCallback)(value)); } catch(e) { exceptionHandler(e); result.reject(e); } }; var wrappedErrback = function(reason) { try { result.resolve((errback || defaultErrback)(reason)); } catch(e) { exceptionHandler(e); result.reject(e); } }; if (pending) { pending.push([wrappedCallback, wrappedErrback]); } else { value.then(wrappedCallback, wrappedErrback); } return result.promise; } } }; return deferred; }; var ref = function(value) { if (value && value.then) return value; return { then: function(callback) { var result = defer(); nextTick(function() { result.resolve(callback(value)); }); return result.promise; } }; }; /** * @ngdoc * @name angular.module.ng.$q#reject * @methodOf angular.module.ng.$q * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in * a promise chain, you don't need to worry about it. * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via * a promise error callback and you want to forward the error to the promise derived from the * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * * <pre> * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; * }, function(reason) { * // error: handle the error if possible and * // resolve promiseB with newPromiseOrValue, * // otherwise forward the rejection to promiseB * if (canHandle(reason)) { * // handle the error and recover * return newPromiseOrValue; * } * return $q.reject(reason); * }); * </pre> * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { return { then: function(callback, errback) { var result = defer(); nextTick(function() { result.resolve((errback || defaultErrback)(reason)); }); return result.promise; } }; }; /** * @ngdoc * @name angular.module.ng.$q#when * @methodOf angular.module.ng.$q * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. * This is useful when you are dealing with on object that might or might not be a promise, or if * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise * @returns {Promise} Returns a single promise that will be resolved with an array of values, * each value coresponding to the promise at the same index in the `promises` array. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ var when = function(value, callback, errback) { var result = defer(), done; var wrappedCallback = function(value) { try { return (callback || defaultCallback)(value); } catch (e) { exceptionHandler(e); return reject(e); } }; var wrappedErrback = function(reason) { try { return (errback || defaultErrback)(reason); } catch (e) { exceptionHandler(e); return reject(e); } }; nextTick(function() { ref(value).then(function(value) { if (done) return; done = true; result.resolve(ref(value).then(wrappedCallback, wrappedErrback)); }, function(reason) { if (done) return; done = true; result.resolve(wrappedErrback(reason)); }); }); return result.promise; }; function defaultCallback(value) { return value; } function defaultErrback(reason) { return reject(reason); } /** * @ngdoc * @name angular.module.ng.$q#all * @methodOf angular.module.ng.$q * @description * Combines multiple promises into a single promise that is resolved when all of the input * promises are resolved. * * @param {Array.<Promise>} promises An array of promises. * @returns {Promise} Returns a single promise that will be resolved with an array of values, * each value coresponding to the promise at the same index in the `promises` array. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ function all(promises) { var deferred = defer(), counter = promises.length, results = []; if (counter) { forEach(promises, function(promise, index) { ref(promise).then(function(value) { if (index in results) return; results[index] = value; if (!(--counter)) deferred.resolve(results); }, function(reason) { if (index in results) return; deferred.reject(reason); }); }); } else { deferred.resolve(results); } return deferred.promise; } return { defer: defer, reject: reject, when: when, all: all }; } /** * @ngdoc object * @name angular.module.ng.$routeProvider * @function * * @description * * Used for configuring routes. See {@link angular.module.ng.$route $route} for an example. */ function $RouteProvider(){ var routes = {}; /** * @ngdoc method * @name angular.module.ng.$routeProvider#when * @methodOf angular.module.ng.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redudant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exacly match the * route definition. * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{function()=}` – Controller fn that should be associated with newly * created scope. * - `template` – `{string=}` – path to an html template that should be used by * {@link angular.module.ng.$compileProvider.directive.ngView ngView} or * {@link angular.module.ng.$compileProvider.directive.ngInclude ngInclude} directives. * - `redirectTo` – {(string|function())=} – value to update * {@link angular.module.ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route template. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() * changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = extend({reloadOnSearch: true}, route); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = {redirectTo: path}; } return this; }; /** * @ngdoc method * @name angular.module.ng.$routeProvider#otherwise * @methodOf angular.module.ng.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', function( $rootScope, $location, $routeParams) { /** * @ngdoc object * @name angular.module.ng.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * @property {Array.<Object>} routes Array of all configured routes. * * @description * Is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * You can define routes through {@link angular.module.ng.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with {@link angular.module.ng.$compileProvider.directive.ngView ngView} * directive and the {@link angular.module.ng.$routeParams $routeParams} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link angular.module.ng.$compileProvider.directive.script inlined templates} to get it working on jsfiddle as well. <example module="ngView"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.template = {{$route.current.template}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { template: 'book.html', controller: BookCntl }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { template: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name angular.module.ng.$route#$beforeRouteChange * @eventOf angular.module.ng.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. * * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name angular.module.ng.$route#$afterRouteChange * @eventOf angular.module.ng.$route * @eventType broadcast on root scope * @description * Broadcasted after a route change. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. */ /** * @ngdoc event * @name angular.module.ng.$route#$routeUpdate * @eventOf angular.module.ng.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var matcher = switchRouteMatcher, dirty = 0, forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name angular.module.ng.$route#reload * @methodOf angular.module.ng.$route * * @description * Causes `$route` service to reload theR current route even if * {@link angular.module.ng.$location $location} hasn't changed. * * As a result of that, {@link angular.module.ng.$compileProvider.directive.ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { dirty++; forceReload = true; } }; $rootScope.$watch(function() { return dirty + $location.url(); }, updateRoute); return $route; ///////////////////////////////////////////////////// function switchRouteMatcher(on, when) { // TODO(i): this code is convoluted and inefficient, we should construct the route matching // regex only once and then reuse it var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$', params = [], dst = {}; forEach(when.split(/\W/), function(param) { if (param) { var paramRegExp = new RegExp(":" + param + "([\\W])"); if (regex.match(paramRegExp)) { regex = regex.replace(paramRegExp, "([^\\/]*)$1"); params.push(param); } } }); var match = on.match(new RegExp(regex)); if (match) { forEach(params, function(name, index) { dst[name] = match[index + 1]; }); } return match ? dst : null; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$route === last.$route && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$beforeRouteChange', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } else { copy(next.params, $routeParams); } } $rootScope.$broadcast('$afterRouteChange', next, last); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; forEach(routes, function(route, path) { if (!match && (params = matcher($location.path(), path))) { match = inherit(route, { params: extend({}, $location.search(), params), pathParams: params}); match.$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parametrs */ function interpolate(string, params) { var result = []; forEach((string||'').split(':'), function(segment, i) { if (i == 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } /** * @ngdoc object * @name angular.module.ng.$routeParams * @requires $route * * @description * Current set of route parameters. The route parameters are a combination of the * {@link angular.module.ng.$location $location} `search()`, and `path()`. The `path` parameters * are extracted when the {@link angular.module.ng.$route $route} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = valueFn({}); } /** * DESIGN NOTES * * The design decisions behind the scope ware heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive from speed as well as memory: * - no closures, instead ups prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the begging (shift) instead of at the end (push) * * Child scopes are created and removed often * - Using array would be slow since inserts in meddle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ /** * @ngdoc object * @name angular.module.ng.$rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc function * @name angular.module.ng.$rootScopeProvider#digestTtl * @methodOf angular.module.ng.$rootScopeProvider * @description * * Sets the number of digest iteration the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc object * @name angular.module.ng.$rootScope * @description * * Every application has a single root {@link angular.module.ng.$rootScope.Scope scope}. * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide * event processing life-cycle. See {@link guide/dev_guide.scopes developer guide on scopes}. */ function $RootScopeProvider(){ var TTL = 10; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; this.$get = ['$injector', '$exceptionHandler', '$parse', function( $injector, $exceptionHandler, $parse) { /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope * * @description * A root scope can be retrieved using the {@link angular.module.ng.$rootScope $rootScope} key from the * {@link angular.module.AUTO.$injector $injector}. Child scopes are created using the * {@link angular.module.ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * <pre> angular.injector(['ng']).invoke(function($rootScope) { var scope = $rootScope.$new(); scope.salutation = 'Hello'; scope.name = 'World'; expect(scope.greeting).toEqual(undefined); scope.$watch('name', function() { this.greeting = this.salutation + ' ' + this.name + '!'; }); // initialize the watch expect(scope.greeting).toEqual(undefined); scope.name = 'Misko'; // still old value, since watches have not been called yet expect(scope.greeting).toEqual(undefined); scope.$digest(); // fire all the watches expect(scope.greeting).toEqual('Hello Misko!'); }); * </pre> * * # Inheritance * A scope can inherit from a parent scope, as in this example: * <pre> var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * </pre> * * # Dependency Injection * See {@link guide/dev_guide.di dependency injection}. * * * @param {Object.<string, function()>=} providers Map of service factory which need to be provided * for the current scope. Defaults to {@link angular.module.ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy when unit-testing and having * the need to override a default service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this['this'] = this.$root = this; this.$$asyncQueue = []; this.$$listeners = {}; } /** * @ngdoc property * @name angular.module.ng.$rootScope.Scope#$id * @propertyOf angular.module.ng.$rootScope.Scope * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ Scope.prototype = { /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$new * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Creates a new child {@link angular.module.ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link angular.module.ng.$rootScope.Scope#$digest $digest()} and * {@link angular.module.ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope * hierarchy using {@link angular.module.ng.$rootScope.Scope#$destroy $destroy()}. * * {@link angular.module.ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for * the scope and its child scopes to be permanently detached from the parent and thus stop * participating in model change detection and listener notification by invoking. * * @params {boolean} isolate if true then the scoped does not prototypically inherit from the * parent scope. The scope is isolated, as it can not se parent scope properties. * When creating widgets it is useful for the widget to not accidently read parent * state. * * @returns {Object} The newly created child scope. * */ $new: function(isolate) { var Child, child; if (isFunction(isolate)) { // TODO: remove at some point throw Error('API-CHANGE: Use $controller to instantiate controllers.'); } if (isolate) { child = new Scope(); child.$root = this.$root; } else { Child = function() {}; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. These will then show up as class // name in the debugger. Child.prototype = this; child = new Child(); child.$id = nextUid(); } child['this'] = child; child.$$listeners = {}; child.$parent = this; child.$$asyncQueue = []; child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; this.$$childTail = child; } else { this.$$childHead = this.$$childTail = child; } return child; }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$watch * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link angular.module.ng.$rootScope.Scope#$digest $digest()} and * should return the value which will be watched. (Since {@link angular.module.ng.$rootScope.Scope#$digest $digest()} * reruns when it detects changes the `watchExpression` can execute multiple times per * {@link angular.module.ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression' are not equal (with the exception of the initial run * see below). The inequality is determined according to * {@link angular.equals} function. To save the value of the object for later comparison * {@link angular.copy} function is used. It also means that watching complex options will * have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This * is achieved by rerunning the watchers until no changes are detected. The rerun iteration * limit is 100 to prevent infinity loop deadlock. * * * If you want to be notified whenever {@link angular.module.ng.$rootScope.Scope#$digest $digest} is called, * you can register an `watchExpression` function with no `listener`. (Since `watchExpression`, * can execute multiple times per {@link angular.module.ng.$rootScope.Scope#$digest $digest} cycle when a change is * detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link angular.module.ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * * # Example <pre> // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); </pre> * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link angular.module.ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a * call to the `listener`. * * - `string`: Evaluated as {@link guide/dev_guide.expressions expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * * - `string`: Evaluated as {@link guide/dev_guide.expressions expression} * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. * * @param {boolean=} objectEquality Compare object for equality rather then for refference. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality) { var scope = this, get = compileToFn(watchExp, 'watch'), array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: watchExp, eq: !!objectEquality }; // in the case user pass string, we need to compile it, do we really need this ? if (!isFunction(listener)) { var listenFn = compileToFn(listener || noop, 'listener'); watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function() { arrayRemove(array, watcher); }; }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$digest * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Process all of the {@link angular.module.ng.$rootScope.Scope#$watch watchers} of the current scope and its children. * Because a {@link angular.module.ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the * `$digest()` keeps calling the {@link angular.module.ng.$rootScope.Scope#$watch watchers} until no more listeners are * firing. This means that it is possible to get into an infinite loop. This function will throw * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 100. * * Usually you don't call `$digest()` directly in * {@link angular.module.ng.$compileProvider.directive.ngController controllers} or in * {@link angular.module.ng.$compileProvider.directive directives}. * Instead a call to {@link angular.module.ng.$rootScope.Scope#$apply $apply()} (typically from within a * {@link angular.module.ng.$compileProvider.directive directives}) will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with {@link angular.module.ng.$rootScope.Scope#$watch $watch()} * with no `listener`. * * You may have a need to call `$digest()` from within unit-tests, to simulate the scope * life-cycle. * * # Example <pre> var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); </pre> * */ $digest: function() { var watch, value, last, watchers, asyncQueue, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], logIdx, logMsg; beginPhase('$digest'); do { dirty = false; current = target; do { asyncQueue = current.$$asyncQueue; while(asyncQueue.length) { try { current.$eval(asyncQueue.shift()); } catch (e) { $exceptionHandler(e); } } if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (typeof value == 'number' && typeof last == 'number' && isNaN(value) && isNaN(last)))) { dirty = true; watch.last = watch.eq ? copy(value) : value; watch.fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; logMsg = (isFunction(watch.exp)) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp; logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); watchLog[logIdx].push(logMsg); } } } catch (e) { $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); if(dirty && !(ttl--)) { clearPhase(); throw Error(TTL + ' $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: ' + toJson(watchLog)); } } while (dirty || asyncQueue.length); clearPhase(); }, /** * @ngdoc event * @name angular.module.$rootScope.Scope#$destroy * @eventOf angular.module.ng.$rootScope.Scope * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. */ /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$destroy * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Remove the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link angular.module.ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link angular.module.ng.$compileProvider.directive.ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it chance to * perform any necessary cleanup. */ $destroy: function() { if ($rootScope == this) return; // we can't remove the root node; var parent = this.$parent; this.$broadcast('$destroy'); if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$eval * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Executes the `expression` on the current scope returning the result. Any exceptions in the * expression are propagated (uncaught). This is useful when evaluating engular expressions. * * # Example <pre> var scope = angular.module.ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); </pre> * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope, locals)`: execute the function with the current `scope` parameter. * @param {Object=} locals Hash object of local variables for the expression. * * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$evalAsync * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: * * - it will execute in the current script execution context (before any DOM rendering). * - at least one {@link angular.module.ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { this.$$asyncQueue.push(expr); }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$apply * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular framework. * (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life-cycle * of {@link angular.module.ng.$exceptionHandler exception handling}, * {@link angular.module.ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/dev_guide.expressions expression} is executed using the * {@link angular.module.ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link angular.module.ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression * was executed using the {@link angular.module.ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { beginPhase('$apply'); return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { clearPhase(); try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); throw e; } } }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$on * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Listen on events of a given type. See {@link angular.module.ng.$rootScope.Scope#$emit $emit} for discussion of * event life cycle. * * @param {string} name Event name to listen on. * @param {function(event)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. * * The event listener function format is: `function(event)`. The `event` object passed into the * listener has the following attributes * * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed. * - `currentScope` - {Scope}: the current scope which is handling the event. * - `name` - {string}: Name of the event. * - `stopPropagation` - {function=}: calling `stopPropagation` function will cancel further event propagation * (available only for events that were `$emit`-ed). * - `preventDefault` - {function}: calling `preventDefault` sets `defaultPrevented` flag to true. * - `defaultPrevented` - {boolean}: true if `preventDefault` was called. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); return function() { arrayRemove(namedListeners, listener); }; }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$emit * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link angular.module.ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link angular.module.ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event traverses upwards toward the root scope and calls all registered * listeners along the way. The event will stop propagating if one of the listeners cancels it. * * Any exception emmited from the {@link angular.module.ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link angular.module.ng.$rootScope.Scope#$on} */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, stopPropagation = false, event = { name: name, targetScope: scope, stopPropagation: function() {stopPropagation = true;}, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i=0, length=namedListeners.length; i<length; i++) { try { namedListeners[i].apply(null, listenerArgs); if (stopPropagation) return event; } catch (e) { $exceptionHandler(e); } } //traverse upwards scope = scope.$parent; } while (scope); return event; }, /** * @ngdoc function * @name angular.module.ng.$rootScope.Scope#$broadcast * @methodOf angular.module.ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link angular.module.ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link angular.module.ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event propagates to all direct and indirect scopes of the current scope and * calls all registered listeners along the way. The event cannot be canceled. * * Any exception emmited from the {@link angular.module.ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link angular.module.ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1); //down while you can, then up and next sibling or up and next sibling until back at root do { current = next; event.currentScope = current; forEach(current.$$listeners[name], function(listener) { try { listener.apply(null, listenerArgs); } catch(e) { $exceptionHandler(e); } }); // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); return event; } }; var $rootScope = new Scope(); return $rootScope; function beginPhase(phase) { if ($rootScope.$$phase) { throw Error($rootScope.$$phase + ' already in progress'); } $rootScope.$$phase = phase; } function clearPhase() { $rootScope.$$phase = null; } function compileToFn(exp, name) { var fn = $parse(exp); assertArgFn(fn, name); return fn; } /** * function used as an initial value for watchers. * because it's uniqueue we can easily tell it apart from other values */ function initWatchVal() {} }]; } /** * !!! This is an undocumented "private" service !!! * * @name angular.module.ng.$sniffer * @requires $window * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} hashchange Does the browser support hashchange event ? * * @description * This is very simple implementation of testing browser's features. */ function $SnifferProvider() { this.$get = ['$window', function($window) { var eventSupport = {}, android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]); return { // Android has history.pushState, but it does not update location correctly // so let's not use the history API at all. // http://code.google.com/p/android/issues/detail?id=17471 // https://github.com/angular/angular.js/issues/904 history: !!($window.history && $window.history.pushState && !(android < 4)), hashchange: 'onhashchange' in $window && // IE8 compatible mode lies (!$window.document.documentMode || $window.document.documentMode > 7), hasEvent: function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. if (event == 'input' && msie == 9) return false; if (isUndefined(eventSupport[event])) { var divElm = $window.document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }, // TODO(i): currently there is no way to feature detect CSP without triggering alerts csp: false }; }]; } /** * @ngdoc object * @name angular.module.ng.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overriden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" /> <button ng-click="$window.alert(greeting)">ALERT</button> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ function $WindowProvider(){ this.$get = valueFn(window); } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = lowercase(trim(line.substr(0, i))); val = trim(line.substr(i + 1)); if (key) { if (parsed[key]) { parsed[key] += ', ' + val; } else { parsed[key] = val; } } }); return parsed; } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { return headersObj[lowercase(name)] || null; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers Http headers getter fn. * @param {(function|Array.<function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, fns) { if (isFunction(fns)) return fns(data, headers); forEach(fns, function(fn) { data = fn(data, headers); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } function $HttpProvider() { var JSON_START = /^\s*(\[|\{[^\{])/, JSON_END = /[\}\]]\s*$/, PROTECTION_PREFIX = /^\)\]\}',?\n/; var $config = this.defaults = { // transform incoming response data transformResponse: [function(data) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(PROTECTION_PREFIX, ''); if (JSON_START.test(data) && JSON_END.test(data)) data = fromJson(data, true); } return data; }], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*', 'X-Requested-With': 'XMLHttpRequest' }, post: {'Content-Type': 'application/json'}, put: {'Content-Type': 'application/json'} } }; var providerResponseInterceptors = this.responseInterceptors = []; this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'), responseInterceptors = []; forEach(providerResponseInterceptors, function(interceptor) { responseInterceptors.push( isString(interceptor) ? $injector.get(interceptor) : $injector.invoke(interceptor) ); }); /** * @ngdoc function * @name angular.module.ng.$http * @requires $httpBacked * @requires $browser * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. * * For unit testing applications that use `$http` service, see * {@link angular.module.ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link angular.module.ngResource.$resource * $resource} service. * * The $http API is based on the {@link angular.module.ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patters this doesn't matter much, for advanced usage, * it is important to familiarize yourself with these apis and guarantees they provide. * * * # General usage * The `$http` service is a function which takes a single argument — a configuration object — * that is used to generate an http request and returns a {@link angular.module.ng.$q promise} * with two $http specific methods: `success` and `error`. * * <pre> * $http({method: 'GET', url: '/someUrl'}). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with status * // code outside of the <200, 400) range * }); * </pre> * * Since the returned value of calling the $http function is a Promise object, you can also use * the `then` method to register callbacks, and these callbacks will receive a single argument – * an object representing the response. See the api signature and type info below for more * details. * * * # Shortcut methods * * Since all invocation of the $http service require definition of the http method and url and * POST and PUT requests require response body/data to be provided as well, shortcut methods * were created to simplify using the api: * * <pre> * $http.get('/someUrl').success(successCallback); * $http.post('/someUrl', data).success(successCallback); * </pre> * * Complete list of shortcut methods: * * - {@link angular.module.ng.$http#get $http.get} * - {@link angular.module.ng.$http#head $http.head} * - {@link angular.module.ng.$http#post $http.post} * - {@link angular.module.ng.$http#put $http.put} * - {@link angular.module.ng.$http#delete $http.delete} * - {@link angular.module.ng.$http#jsonp $http.jsonp} * * * # Setting HTTP Headers * * The $http service will automatically add certain http headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `X-Requested-With: XMLHttpRequest` * - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from this configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with name equal to the lower-cased http method name, e.g. * `$httpProvider.defaults.headers.get['My-Header']='value'`. * * Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar * fassion as described above. * * * # Transforming Requests and Responses * * Both requests and responses can be transformed using transform functions. By default, Angular * applies these transformations: * * Request transformations: * * - if the `data` property of the request config object contains an object, serialize it into * JSON format. * * Response transformations: * * - if XSRF prefix is detected, strip it (see Security Considerations section below) * - if json response is detected, deserialize it using a JSON parser * * To override these transformation locally, specify transform functions as `transformRequest` * and/or `transformResponse` properties of the config object. To globally override the default * transforms, override the `$httpProvider.defaults.transformRequest` and * `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`. * * * # Caching * * To enable caching set the configuration property `cache` to `true`. When the cache is * enabled, `$http` stores the response from the server in local cache. Next time the * response is served from the cache without sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same url that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response for the first request. * * * # Response interceptors * * Before you start creating interceptors, be sure to understand the * {@link angular.module.ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication or any kind of synchronous or * asynchronous preprocessing of received responses, it is desirable to be able to intercept * responses for http requests before they are handed over to the application code that * initiated these requests. The response interceptors leverage the {@link angular.module.ng.$q * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. * * The interceptors are service factories that are registered with the $httpProvider by * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor — a function that * takes a {@link angular.module.ng.$q promise} and returns the original or a new promise. * * <pre> * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return function(promise) { * return promise.then(function(response) { * // do something on success * }, function(response) { * // do something on error * if (canRecover(response)) { * return responseOrNewPromise * } * return $q.reject(response); * }); * } * }); * * $httpProvider.responseInterceptors.push('myHttpInterceptor'); * * * // register the interceptor via an anonymous factory * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { * return function(promise) { * // same as above * } * }); * </pre> * * * # Security Considerations * * When designing web applications, consider security threats from: * * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON Vulnerability} allows third party web-site to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * Angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which * an unauthorized site can gain your user's private data. Angular provides following mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that * runs on your domain could read the cookie, your server can be assured that the XHR came from * JavaScript running on your domain. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have read the token. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript making * up its own tokens). We recommend that the token is a digest of your site's authentication * cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server. * - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * response body and headers and returns its transformed (typically deserialized) version. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link angular.module.ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number}` – timeout in milliseconds. * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 * requests with credentials} for more information. * * @returns {HttpPromise} Returns a {@link angular.module.ng.$q promise} object with the * standard `then` method and two http specific methods: `success` and `error`. The `then` * method takes two arguments a success and an error callback which will be called with a * response object. The `success` and `error` methods take a single argument - a function that * will be called when the request succeeds or fails respectively. The arguments passed into * these functions are destructured representation of the response object passed into the * `then` method. The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example> <file name="index.html"> <div ng-controller="FetchCtrl"> <select ng-model="method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80"/> <button ng-click="fetch()">fetch</button><br> <button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> function FetchCtrl($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). success(function(data, status) { $scope.status = status; $scope.data = data; }). error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; } </file> <file name="http-hello.html"> Hello, $http! </file> <file name="scenario.js"> it('should make an xhr GET request', function() { element(':button:contains("Sample GET")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Hello, \$http!/); }); it('should make a JSONP request to angularjs.org', function() { element(':button:contains("Sample JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Super Hero!/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { element(':button:contains("Invalid JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('0'); expect(binding('data')).toBe('Request failed'); }); </file> </example> */ function $http(config) { config.method = uppercase(config.method); var reqTransformFn = config.transformRequest || $config.transformRequest, respTransformFn = config.transformResponse || $config.transformResponse, defHeaders = $config.headers, reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']}, defHeaders.common, defHeaders[lowercase(config.method)], config.headers), reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn), promise; // strip content-type if data is undefined if (isUndefined(config.data)) { delete reqHeaders['Content-Type']; } // send request promise = sendReq(config, reqData, reqHeaders); // transform future response promise = promise.then(transformResponse, transformResponse); // apply interceptors forEach(responseInterceptors, function(interceptor) { promise = interceptor(promise); }); promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response, { data: transformData(response.data, response.headers, respTransformFn) }); return (isSuccess(response.status)) ? resp : $q.reject(resp); } } $http.pendingRequests = []; /** * @ngdoc method * @name angular.module.ng.$http#get * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `GET` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name angular.module.ng.$http#delete * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `DELETE` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name angular.module.ng.$http#head * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `HEAD` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name angular.module.ng.$http#jsonp * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `JSONP` request * * @param {string} url Relative or absolute URL specifying the destination of the request. * Should contain `JSON_CALLBACK` string. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name angular.module.ng.$http#post * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `POST` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name angular.module.ng.$http#put * @methodOf angular.module.ng.$http * * @description * Shortcut method to perform `PUT` request * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put'); /** * @ngdoc property * @name angular.module.ng.$http#defaults * @propertyOf angular.module.ng.$http * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = $config; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend(config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend(config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request * * !!! ACCESSES CLOSURE VARS: * $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData, reqHeaders) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, url = buildUrl(config.url, config.params); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if (config.cache && config.method == 'GET') { cache = isObject(config.cache) ? config.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (cachedResp) { if (cachedResp.then) { // cached request has already been sent, but there is no response yet cachedResp.then(removePendingReq, removePendingReq); return cachedResp; } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); } else { resolvePromise(cachedResp, 200, {}); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, send the request to the backend if (!cachedResp) { $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString)]); } else { // remove promise from the cache cache.remove(url); } } resolvePromise(response, status, headersString); $rootScope.$apply(); } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers) { // normalize internal statuses to 0 status = Math.max(status, 0); (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config }); } function removePendingReq() { var idx = indexOf($http.pendingRequests, config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, params) { if (!params) return url; var parts = []; forEachSorted(params, function(value, key) { if (value == null || value == undefined) return; if (isObject(value)) { value = toJson(value); } parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); }); return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } }]; } var XHR = window.XMLHttpRequest || function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; /** * @ngdoc object * @name angular.module.ng.$httpBackend * @requires $browser * @requires $window * @requires $document * * @description * HTTP backend used by the {@link angular.module.ng.$http service} that delegates to * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * * You should never need to use this service directly, instead use the higher-level abstractions: * {@link angular.module.ng.$http $http} or {@link angular.module.ngResource.$resource $resource}. * * During testing this implementation is swapped with {@link angular.module.ngMock.$httpBackend mock * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, $document[0], $window.location.protocol.replace(':', '')); }]; } function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials) { $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); if (lowercase(method) == 'jsonp') { var callbackId = '_' + (callbacks.counter++).toString(36); callbacks[callbackId] = function(data) { callbacks[callbackId].data = data; }; jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), function() { if (callbacks[callbackId].data) { completeRequest(callback, 200, callbacks[callbackId].data); } else { completeRequest(callback, -2); } delete callbacks[callbackId]; }); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (value) xhr.setRequestHeader(key, value); }); var status; // In IE6 and 7, this might be called synchronously when xhr.send below is called and the // response is in the cache. the promise api will ensure that to the app code the api is // always async xhr.onreadystatechange = function() { if (xhr.readyState == 4) { completeRequest( callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders()); } }; if (withCredentials) { xhr.withCredentials = true; } xhr.send(post || ''); if (timeout > 0) { $browserDefer(function() { status = -1; xhr.abort(); }, timeout); } } function completeRequest(callback, status, response, headersString) { // URL_MATCH is defined in src/service/location.js var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1]; // fix status code for file protocol (it's always 0) status = (protocol == 'file') ? (response ? 200 : 404) : status; // normalize IE bug (http://bugs.jquery.com/ticket/1450) status = status == 1223 ? 204 : status; callback(status, response, headersString); $browser.$$completeOutstandingRequest(noop); } }; function jsonpReq(url, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'), doneWrapper = function() { rawDocument.body.removeChild(script); if (done) done(); }; script.type = 'text/javascript'; script.src = url; if (msie) { script.onreadystatechange = function() { if (/loaded|complete/.test(script.readyState)) doneWrapper(); }; } else { script.onload = script.onerror = doneWrapper; } rawDocument.body.appendChild(script); } } /** * @ngdoc object * @name angular.module.ng.$locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ function $LocaleProvider(){ this.$get = function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }; } function $TimeoutProvider() { this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', function($rootScope, $browser, $q, $exceptionHandler) { var deferreds = {}; /** * @ngdoc function * @name angular.module.ng.$timeout * @requires $browser * * @description * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch * block and delegates any exceptions to * {@link angular.module.ng.$exceptionHandler $exceptionHandler} service. * * The return value of registering a timeout function is a promise which will be resolved when * the timeout is reached and the timeout function is executed. * * To cancel a the timeout request, call `$timeout.cancel(promise)`. * * In tests you can use {@link angular.module.ngMock.$timeout `$timeout.flush()`} to * synchronously flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be delayed. * @param {number=} [delay=0] Delay in milliseconds. * @param {boolean=} [invokeApply=true] If set to false skips model dirty checking, otherwise * will invoke `fn` within the {@link angular.module.ng.$rootScope.Scope#$apply $apply} block. * @returns {*} Promise that will be resolved when the timeout is reached. The value this * promise will be resolved with is the return value of the `fn` function. */ function timeout(fn, delay, invokeApply) { var deferred = $q.defer(), promise = deferred.promise, skipApply = (isDefined(invokeApply) && !invokeApply), timeoutId, cleanup; timeoutId = $browser.defer(function() { try { deferred.resolve(fn()); } catch(e) { deferred.reject(e); $exceptionHandler(e); } if (!skipApply) $rootScope.$apply(); }, delay); cleanup = function() { delete deferreds[promise.$$timeoutId]; }; promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; promise.then(cleanup, cleanup); return promise; } /** * @ngdoc function * @name angular.module.ng.$timeout#cancel * @methodOf angular.module.ng.$timeout * * @description * Cancels a task associated with the `promise`. As a result of this the promise will be * resolved with a rejection. * * @param {Promise} promise Promise returned by the `$timeout` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ timeout.cancel = function(promise) { if (promise.$$timeoutId in deferreds) { deferreds[promise.$$timeoutId].reject('canceled'); return $browser.defer.cancel(promise.$$timeoutId); } return false; }; return timeout; }]; } /** * @ngdoc object * @name angular.module.ng.$filterProvider * @description * * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To * achieve this a filter definition consists of a factory function which is annotated with dependencies and is * responsible for creating a the filter function. * * <pre> * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!'; * }); * * // register a filter factory which uses the * // greet service to demonstrate DI. * $filterProvider.register('greet', function(greet){ * // return the filter function which uses the greet service * // to generate salutation * return function(text) { * // filters need to be forgiving so check input validity * return text && greet(text) || text; * }; * }); * } * </pre> * * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`. * <pre> * it('should be the same instance', inject( * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); * </pre> * * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @ngdoc method * @name angular.module.ng.$filterProvider#register * @methodOf angular.module.ng.$filterProvider * @description * Register filter factory function. * * @param {String} name Name of the filter. * @param {function} fn The filter factory function which is injectable. */ /** * @ngdoc function * @name angular.module.ng.$filter * @function * @description * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression | [ filter_name ] }} * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; function register(name, factory) { return $provide.factory(name + suffix, factory); } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); } }]; //////////////////////////////////////// register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); register('json', jsonFilter); register('limitTo', limitToFilter); register('lowercase', lowercaseFilter); register('number', numberFilter); register('orderBy', orderByFilter); register('uppercase', uppercaseFilter); } /** * @ngdoc filter * @name angular.module.ng.$filter.filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.module.ng.$filter} for more information about Angular arrays. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @example <doc:example> <doc:source> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}]"></div> Search: <input ng-model="searchText"> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng-repeat="friend in friends | filter:searchText"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> <hr> Any: <input ng-model="search.$"> <br> Name only <input ng-model="search.name"><br> Phone only <input ng-model="search.phone"å><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng-repeat="friend in friends | filter:search"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Julie']); }); </doc:scenario> </doc:example> */ function filterFilter() { return function(array, expression) { if (!(array instanceof Array)) return array; var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function() { var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function() { var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; } } /** * @ngdoc filter * @name angular.module.ng.$filter.currency * @function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.amount = 1234.56; } </script> <div ng-controller="Ctrl"> <input type="number" ng-model="amount"> <br> default currency symbol ($): {{amount | currency}}<br> custom currency identifier (USD$): {{amount | currency:"USD$"}} </div> </doc:source> <doc:scenario> it('should init with 1234.56', function() { expect(binding('amount | currency')).toBe('$1,234.56'); expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); }); it('should update', function() { input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('($1,234.00)'); expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); }); </doc:scenario> </doc:example> */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(amount, currencySymbol){ if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). replace(/\u00A4/g, currencySymbol); }; } /** * @ngdoc filter * @name angular.module.ng.$filter.number * @function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.val = 1234.56789; } </script> <div ng-controller="Ctrl"> Enter number: <input ng-model='val'><br> Default formatting: {{val | number}}<br> No fractions: {{val | number:0}}<br> Negative number: {{-val | number:4}} </div> </doc:source> <doc:scenario> it('should format numbers', function() { expect(binding('val | number')).toBe('1,234.568'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function() { input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.333'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; } var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (isNaN(number) || !isFinite(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; if (numStr.indexOf('e') !== -1) { formatedText = numStr; } else { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } var pow = Math.pow(10, fractionSize); number = Math.round(number * pow) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (var i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize); } parts.push(isNegative ? pattern.negPre : pattern.posPre); parts.push(formatedText); parts.push(isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var offset = date.getTimezoneOffset(); return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, NUMBER_STRING = /^\d+$/; /** * @ngdoc filter * @name angular.module.ng.$filter.date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200) * * `format` string can also be one of the following predefined * {@link guide/dev_guide.i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence * (e.g. `"h o''clock"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: {{1288323623006 | date:'medium'}}<br> <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br> <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br> </doc:source> <doc:scenario> it('should format date', function() { expect(binding("1288323623006 | date:'medium'")). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); </doc:scenario> </doc:example> */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; function jsonStringToDate(string){ var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0)); return date; } return string; } return function(date, format) { var text = '', parts = [], fn, match; format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = int(date); } else { date = jsonStringToDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; } /** * @ngdoc filter * @name angular.module.ng.$filter.json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * * @example: <doc:example> <doc:source> <pre>{{ {'name':'value'} | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); }); </doc:scenario> </doc:example> * */ function jsonFilter() { return function(object) { return toJson(object, true); }; } /** * @ngdoc filter * @name angular.module.ng.$filter.lowercase * @function * @description * Converts string to lowercase. * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name angular.module.ng.$filter.uppercase * @function * @description * Converts string to uppercase. * @see angular.uppercase */ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc function * @name angular.module.ng.$filter.limitTo * @function * * @description * Creates a new array containing only a specified number of elements in an array. The elements * are taken from either the beginning or the end of the source array, as specified by the * value and sign (positive or negative) of `limit`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link angular.module.ng.$filter} for more information about Angular arrays. * * @param {Array} array Source array to be limited. * @param {string|Number} limit The length of the returned array. If the `limit` number is * positive, `limit` number of items from the beginning of the source array are copied. * If the number is negative, `limit` number of items from the end of the source array are * copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit` * elements. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.limit = 3; } </script> <div ng-controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng-model="limit"> <p>Output: {{ numbers | limitTo:limit }}</p> </div> </doc:source> <doc:scenario> it('should limit the numer array to first three items', function() { expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3'); expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]'); }); it('should update the output when -3 is entered', function() { input('limit').enter(-3); expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]'); }); it('should not exceed the maximum size of input array', function() { input('limit').enter(100); expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]'); }); </doc:scenario> </doc:example> */ function limitToFilter(){ return function(array, limit) { if (!(array instanceof Array)) return array; limit = int(limit); var out = [], i, n; // check that array is iterable if (!array || !(array instanceof Array)) return out; // if abs(limit) exceeds maximum length, trim it if (limit > array.length) limit = array.length; else if (limit < -array.length) limit = -array.length; if (limit > 0) { i = 0; n = limit; } else { i = array.length + limit; n = array.length; } for (; i<n; i++) { out.push(array[i]); } return out; } } /** * @ngdoc function * @name angular.module.ng.$filter.orderBy * @function * * @description * Orders a specified `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in Angular expressions. See * {@link angular.module.ng.$filter} for more informaton about Angular arrays. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control * ascending or descending sort order (for example, +name or -name). * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}] $scope.predicate = '-age'; } </script> <div ng-controller="Ctrl"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> (<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> <tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> <tr> </table> </div> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('-age'); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse){ return function(array, sortPredicate, reverseOrder) { if (!(array instanceof Array)) return array; if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = $parse(predicate); } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } } } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive } } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } /* * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with `ngClick` directive * without changing the location or causing page reloads, e.g.: * <a href="" ng-click="model.$save()">Save</a> */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { // turn <a href ng-click="..">link</a> into a link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!attr.href) { attr.$set('href', ''); } return function(scope, element) { element.bind('click', function(event){ // if we have no href url, then don't navigate anywhere. if (!element.attr('href')) { event.preventDefault(); } }); } } }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngHref * @restrict A * * @description * Using Angular markup like {{hash}} in an href attribute makes * the page open to a wrong URL, if the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ngHref` directive solves this problem. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </doc:source> <doc:scenario> it('should execute ng-click but not reload when href without value', function() { element('#link-1').click(); expect(input('value').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng-click but not reload when href empty string', function() { element('#link-2').click(); expect(input('value').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng-click and change url when ng-href specified', function() { expect(element('#link-3').attr('href')).toBe("/123"); element('#link-3').click(); expect(browser().window().path()).toEqual('/123'); }); it('should execute ng-click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(input('value').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { element('#link-5').click(); expect(input('value').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(''); }); it('should only change url when only ng-href', function() { input('value').enter('6'); expect(element('#link-6').attr('href')).toBe('6'); element('#link-6').click(); expect(browser().location().url()).toEqual('/6'); }); </doc:scenario> </doc:example> */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngSrc * @restrict A * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngDisabled * @restrict A * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * <pre> * <div ng-init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * </pre> * * The HTML specs do not require browsers to preserve the special attributes such as disabled. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngDisabled` directive. * * @example <doc:example> <doc:source> Click me to toggle: <input type="checkbox" ng-model="checked"><br/> <button ng-model="button" ng-disabled="checked">Button</button> </doc:source> <doc:scenario> it('should toggle button', function() { expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngDisabled Angular expression that will be evaluated. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngChecked * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as checked. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngChecked` directive. * @example <doc:example> <doc:source> Check me to check both: <input type="checkbox" ng-model="master"><br/> <input id="checkSlave" type="checkbox" ng-checked="master"> </doc:source> <doc:scenario> it('should check both checkBoxes', function() { expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); input('master').check(); expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngChecked Angular expression that will be evaluated. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMultiple * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as multiple. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngMultiple` directive. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng-model="checked"><br/> <select id="select" ng-multiple="checked"> <option>Misko</option> <option>Igor</option> <option>Vojta</option> <option>Di</option> </select> </doc:source> <doc:scenario> it('should toggle multiple', function() { expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element SELECT * @param {expression} ngMultiple Angular expression that will be evaluated. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngReadonly * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as readonly. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngReadonly` directive. * @example <doc:example> <doc:source> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </doc:source> <doc:scenario> it('should toggle readonly attr', function() { expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {string} expression Angular expression that will be evaluated. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngSelected * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as selected. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduced the `ngSelected` directive. * @example <doc:example> <doc:source> Check me to select: <input type="checkbox" ng-model="selected"><br/> <select> <option>Hello!</option> <option id="greet" ng-selected="selected">Greetings!</option> </select> </doc:source> <doc:scenario> it('should select Greetings!', function() { expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); input('selected').check(); expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element OPTION * @param {string} expression Angular expression that will be evaluated. */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 100, compile: function() { return function(scope, element, attr) { attr.$$observers[attrName] = []; scope.$watch(attr[normalized], function(value) { attr.$set(attrName, !!value); }); }; } }; }; }); // ng-src, ng-href are interpolated forEach(['src', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated compile: function() { return function(scope, element, attr) { var value = attr[normalized]; if (value == undefined) { // undefined value means that the directive is being interpolated // so just register observer attr.$$observers[attrName] = []; attr.$observe(normalized, function(value) { attr.$set(attrName, value); // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect if (msie) element.prop(attrName, value); }); } else { // value present means that no interpolation, so copy to native attribute. attr.$set(attrName, value); element.prop(attrName, value); } }; } }; }; }); var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, $setDirty: noop }; /** * @ngdoc object * @name angular.module.ng.$compileProvider.directive.form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containg forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. * * @property {Object} $error Is an object hash, containing references to all invalid controls or * forms, where: * * - keys are validation tokens (error names) — such as `REQUIRED`, `URL` or `EMAIL`), * - values are arrays of controls or forms that are invalid with given error. * * @description * `FormController` keeps track of all its controls and nested forms as well as state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link angular.module.ng.$compileProvider.directive.form form} directive creates an instance * of `FormController`. * */ //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope']; function FormController(element, attrs) { var form = this, parentForm = element.parent().controller('form') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid errors = form.$error = {}; // init state form.$name = attrs.name; form.$dirty = false; form.$pristine = true; form.$valid = true; form.$invalid = false; parentForm.$addControl(form); // Setup initial state of the control element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } form.$addControl = function(control) { if (control.$name && !form.hasOwnProperty(control.$name)) { form[control.$name] = control; } }; form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); }; form.$setValidity = function(validationToken, isValid, control) { var queue = errors[validationToken]; if (isValid) { if (queue) { arrayRemove(queue, control); if (!queue.length) { invalidCount--; if (!invalidCount) { toggleValidCss(isValid); form.$valid = true; form.$invalid = false; } errors[validationToken] = false; toggleValidCss(true, validationToken); parentForm.$setValidity(validationToken, true, form); } } } else { if (!invalidCount) { toggleValidCss(isValid); } if (queue) { if (includes(queue, control)) return; } else { errors[validationToken] = queue = []; invalidCount++; toggleValidCss(false, validationToken); parentForm.$setValidity(validationToken, false, form); } queue.push(control); form.$valid = false; form.$invalid = true; } }; form.$setDirty = function() { element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); form.$dirty = true; form.$pristine = false; }; } /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngForm * @restrict EAC * * @description * Nestable alias of {@link angular.module.ng.$compileProvider.directive.form `form`} directive. HTML * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.form * @restrict E * * @description * Directive that instantiates * {@link angular.module.ng.$compileProvider.directive.form.FormController FormController}. * * If `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link angular.module.ng.$compileProvider.directive.ngForm `ngForm`} * * In angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this * reason angular provides {@link angular.module.ng.$compileProvider.directive.ngForm `ngForm`} alias * which behaves identical to `<form>` but allows form nesting. * * * # CSS classes * - `ng-valid` Is set if the form is valid. * - `ng-invalid` Is set if the form is invalid. * - `ng-pristine` Is set if the form is pristine. * - `ng-dirty` Is set if the form is dirty. * * * # Submitting a form and preventing default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in application specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `<form>` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when * a form is submitted: * * - {@link angular.module.ng.$compileProvider.directive.ngSubmit ngSubmit} directive on the form element * - {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This * is because of the following form submission rules coming from the html spec: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.userType = 'guest'; } </script> <form name="myForm" ng-controller="Ctrl"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.REQUIRED">Required!</span><br> <tt>userType = {{userType}}</tt><br> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('userType')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('userType').enter(''); expect(binding('userType')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var formDirectiveDir = { name: 'form', restrict: 'E', controller: FormController, compile: function() { return { pre: function(scope, formElement, attr, controller) { if (!attr.action) { formElement.bind('submit', function(event) { event.preventDefault(); }); } var parentFormCtrl = formElement.parent().controller('form'), alias = attr.name || attr.ngForm; if (alias) { scope[alias] = controller; } if (parentFormCtrl) { formElement.bind('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { scope[alias] = undefined; } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); } } }; } }; var formDirective = valueFn(formDirectiveDir); var ngFormDirective = valueFn(extend(copy(formDirectiveDir), {restrict: 'EAC'})); var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var inputType = { /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.text * * @description * Standard HTML text input with angular data binding. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'guest'; $scope.word = /^\w*$/; } </script> <form name="myForm" ng-controller="Ctrl"> Single word: <input type="text" name="input" ng-model="text" ng-pattern="word" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if multi word', function() { input('text').enter('hello world'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'text': textInputType, /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.number * * @description * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less then `min`. * @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value = 12; } </script> <form name="myForm" ng-controller="Ctrl"> Number: <input type="number" name="input" ng-model="value" min="0" max="99" required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <span class="error" ng-show="myForm.list.$error.number"> Not valid number!</span> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('value')).toEqual('12'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('value').enter(''); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if over max', function() { input('value').enter('123'); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'number': numberInputType, /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.url * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'http://google.com'; } </script> <form name="myForm" ng-controller="Ctrl"> URL: <input type="url" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.url"> Not valid url!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('http://google.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not url', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'url': urlInputType, /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.email * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = '[email protected]'; } </script> <form name="myForm" ng-controller="Ctrl"> Email: <input type="email" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('[email protected]'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not email', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'email': emailInputType, /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.radio * * @description * HTML radio button. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.color = 'blue'; } </script> <form name="myForm" ng-controller="Ctrl"> <input type="radio" ng-model="color" value="red"> Red <br/> <input type="radio" ng-model="color" value="green"> Green <br/> <input type="radio" ng-model="color" value="blue"> Blue <br/> <tt>color = {{color}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('color')).toEqual('blue'); input('color').select('red'); expect(binding('color')).toEqual('red'); }); </doc:scenario> </doc:example> */ 'radio': radioInputType, /** * @ngdoc inputType * @name angular.module.ng.$compileProvider.directive.input.checkbox * * @description * HTML checkbox. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngTrueValue The value to which the expression should be set when selected. * @param {string=} ngFalseValue The value to which the expression should be set when not selected. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value1 = true; $scope.value2 = 'YES' } </script> <form name="myForm" ng-controller="Ctrl"> Value1: <input type="checkbox" ng-model="value1"> <br/> Value2: <input type="checkbox" ng-model="value2" ng-true-value="YES" ng-false-value="NO"> <br/> <tt>value1 = {{value1}}</tt><br/> <tt>value2 = {{value2}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('value1')).toEqual('true'); expect(binding('value2')).toEqual('YES'); input('value1').check(); input('value2').check(); expect(binding('value1')).toEqual('false'); expect(binding('value2')).toEqual('NO'); }); </doc:scenario> </doc:example> */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, 'reset': noop }; function isEmpty(value) { return isUndefined(value) || value === '' || value === null || value !== value; } function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { var listener = function() { var value = trim(element.val()); if (ctrl.$viewValue !== value) { scope.$apply(function() { ctrl.$setViewValue(value); }); } }; // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { element.bind('input', listener); } else { var timeout; element.bind('keydown', function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; if (!timeout) { timeout = $browser.defer(function() { listener(); timeout = null; }); } }); // if user paste into input using mouse, we need "change" event to catch it element.bind('change', listener); } ctrl.$render = function() { element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; // pattern validator var pattern = attr.ngPattern, patternValidator; var validate = function(regexp, value) { if (isEmpty(value) || regexp.test(value)) { ctrl.$setValidity('pattern', true); return value; } else { ctrl.$setValidity('pattern', false); return undefined; } }; if (pattern) { if (pattern.match(/^\/(.*)\/$/)) { pattern = new RegExp(pattern.substr(1, pattern.length - 2)); patternValidator = function(value) { return validate(pattern, value) }; } else { patternValidator = function(value) { var patternObj = scope.$eval(pattern); if (!patternObj || !patternObj.test) { throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); } return validate(patternObj, value); }; } ctrl.$formatters.push(patternValidator); ctrl.$parsers.push(patternValidator); } // min length validator if (attr.ngMinlength) { var minlength = int(attr.ngMinlength); var minLengthValidator = function(value) { if (!isEmpty(value) && value.length < minlength) { ctrl.$setValidity('minlength', false); return undefined; } else { ctrl.$setValidity('minlength', true); return value; } }; ctrl.$parsers.push(minLengthValidator); ctrl.$formatters.push(minLengthValidator); } // max length validator if (attr.ngMaxlength) { var maxlength = int(attr.ngMaxlength); var maxLengthValidator = function(value) { if (!isEmpty(value) && value.length > maxlength) { ctrl.$setValidity('maxlength', false); return undefined; } else { ctrl.$setValidity('maxlength', true); return value; } }; ctrl.$parsers.push(maxLengthValidator); ctrl.$formatters.push(maxLengthValidator); } } function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$parsers.push(function(value) { var empty = isEmpty(value); if (empty || NUMBER_REGEXP.test(value)) { ctrl.$setValidity('number', true); return value === '' ? null : (empty ? value : parseFloat(value)); } else { ctrl.$setValidity('number', false); return undefined; } }); ctrl.$formatters.push(function(value) { return isEmpty(value) ? '' : '' + value; }); if (attr.min) { var min = parseFloat(attr.min); var minValidator = function(value) { if (!isEmpty(value) && value < min) { ctrl.$setValidity('min', false); return undefined; } else { ctrl.$setValidity('min', true); return value; } }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } if (attr.max) { var max = parseFloat(attr.max); var maxValidator = function(value) { if (!isEmpty(value) && value > max) { ctrl.$setValidity('max', false); return undefined; } else { ctrl.$setValidity('max', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } ctrl.$formatters.push(function(value) { if (isEmpty(value) || isNumber(value)) { ctrl.$setValidity('number', true); return value; } else { ctrl.$setValidity('number', false); return undefined; } }); } function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var urlValidator = function(value) { if (isEmpty(value) || URL_REGEXP.test(value)) { ctrl.$setValidity('url', true); return value; } else { ctrl.$setValidity('url', false); return undefined; } }; ctrl.$formatters.push(urlValidator); ctrl.$parsers.push(urlValidator); } function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var emailValidator = function(value) { if (isEmpty(value) || EMAIL_REGEXP.test(value)) { ctrl.$setValidity('email', true); return value; } else { ctrl.$setValidity('email', false); return undefined; } }; ctrl.$formatters.push(emailValidator); ctrl.$parsers.push(emailValidator); } function radioInputType(scope, element, attr, ctrl) { // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } element.bind('click', function() { if (element[0].checked) { scope.$apply(function() { ctrl.$setViewValue(attr.value); }); } }); ctrl.$render = function() { var value = attr.value; element[0].checked = (value == ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } function checkboxInputType(scope, element, attr, ctrl) { var trueValue = attr.ngTrueValue, falseValue = attr.ngFalseValue; if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; element.bind('click', function() { scope.$apply(function() { ctrl.$setViewValue(element[0].checked); }); }); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; ctrl.$formatters.push(function(value) { return value === trueValue; }); ctrl.$parsers.push(function(value) { return value ? trueValue : falseValue; }); } /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.textarea * * @description * HTML textarea element control with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link angular.module.ng.$compileProvider.directive.input input element}. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.input * @restrict E * * @description * HTML input element control with angular data-binding. Input control follows HTML5 input types * and polyfills the HTML5 validation behavior for older browsers. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.user = {name: 'guest', last: 'visitor'}; } </script> <div ng-controller="Ctrl"> <form name="myForm"> User name: <input type="text" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required"> Required!</span><br> Last name: <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10"> <span class="error" ng-show="myForm.lastName.$error.minlength"> Too short!</span> <span class="error" ng-show="myForm.lastName.$error.maxlength"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if empty when required', function() { input('user.name').enter(''); expect(binding('user')).toEqual('{"last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('false'); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be valid if empty when min length is set', function() { input('user.last').enter(''); expect(binding('user')).toEqual('{"name":"guest","last":""}'); expect(binding('myForm.lastName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if less than required min length', function() { input('user.last').enter('xx'); expect(binding('user')).toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/minlength/); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be invalid if longer than max length', function() { input('user.last').enter('some ridiculously long name'); expect(binding('user')) .toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); expect(binding('myForm.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { return { restrict: 'E', require: '?ngModel', link: function(scope, element, attr, ctrl) { if (ctrl) { (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, $browser); } } }; }]; var VALID_CLASS = 'ng-valid', INVALID_CLASS = 'ng-invalid', PRISTINE_CLASS = 'ng-pristine', DIRTY_CLASS = 'ng-dirty'; /** * @ngdoc object * @name angular.module.ng.$compileProvider.directive.ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model, that the control is bound to. * @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes * all of these functions to sanitize / convert the value as well as validate. * * @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of * these functions to convert the value as well as validate. * * @property {Object} $error An bject hash with all errors as keys. * * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. * @property {boolean} $valid True if there is no error. * @property {boolean} $invalid True if at least one error on the control. * * @description * */ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel', '$element', function($scope, $exceptionHandler, $attr, ngModel, $element) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$parsers = []; this.$formatters = []; this.$viewChangeListeners = []; this.$pristine = true; this.$dirty = false; this.$valid = true; this.$invalid = false; this.$render = noop; this.$name = $attr.name; var parentForm = $element.inheritedData('$formController') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid $error = this.$error = {}; // keep invalid keys here // Setup initial state of the control $element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; $element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } /** * @ngdoc function * @name angular.module.ng.$compileProvider.directive.ngModel.NgModelController#$setValidity * @methodOf angular.module.ng.$compileProvider.directive.ngModel.NgModelController * * @description * Change the validity state, and notifies the form when the control changes validity. (i.e. it * does not notify form if given validator is already marked as invalid). * * This method should be called by validators - i.e. the parser or formatter functions. * * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). */ this.$setValidity = function(validationErrorKey, isValid) { if ($error[validationErrorKey] === !isValid) return; if (isValid) { if ($error[validationErrorKey]) invalidCount--; if (!invalidCount) { toggleValidCss(true); this.$valid = true; this.$invalid = false; } } else { toggleValidCss(false); this.$invalid = true; this.$valid = false; invalidCount++; } $error[validationErrorKey] = !isValid; toggleValidCss(isValid, validationErrorKey); parentForm.$setValidity(validationErrorKey, isValid, this); }; /** * @ngdoc function * @name angular.module.ng.$compileProvider.directive.ngModel.NgModelController#$setViewValue * @methodOf angular.module.ng.$compileProvider.directive.ngModel.NgModelController * * @description * Read a value from view. * * This method should be called from within a DOM event handler. * For example {@link angular.module.ng.$compileProvider.directive.input input} or * {@link angular.module.ng.$compileProvider.directive.select select} directives call it. * * It internally calls all `formatters` and if resulted value is valid, updates the model and * calls all registered change listeners. * * @param {string} value Value from the view. */ this.$setViewValue = function(value) { this.$viewValue = value; // change to dirty if (this.$pristine) { this.$dirty = true; this.$pristine = false; $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); parentForm.$setDirty(); } forEach(this.$parsers, function(fn) { value = fn(value); }); if (this.$modelValue !== value) { this.$modelValue = value; ngModel(value); forEach(this.$viewChangeListeners, function(listener) { try { listener(); } catch(e) { $exceptionHandler(e); } }) } }; // model -> value var ctrl = this; $scope.$watch(function() { return ngModel(); }, function(value) { // ignore change from view if (ctrl.$modelValue === value) return; var formatters = ctrl.$formatters, idx = formatters.length; ctrl.$modelValue = value; while(idx--) { value = formatters[idx](value); } if (ctrl.$viewValue !== value) { ctrl.$viewValue = value; ctrl.$render(); } }); }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngModel * * @element input * * @description * Is directive that tells Angular to do two-way data binding. It works together with `input`, * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well. * * `ngModel` is responsible for: * * - binding the view into the model, which other directives such as `input`, `textarea` or `select` * require, * - providing validation behavior (i.e. required, number, email, url), * - keeping state of the control (valid/invalid, dirty/pristine, validation errors), * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), * - register the control with parent {@link angular.module.ng.$compileProvider.directive.form form}. * * For basic examples, how to use `ngModel`, see: * * - {@link angular.module.ng.$compileProvider.directive.input input} * - {@link angular.module.ng.$compileProvider.directive.input.text text} * - {@link angular.module.ng.$compileProvider.directive.input.checkbox checkbox} * - {@link angular.module.ng.$compileProvider.directive.input.radio radio} * - {@link angular.module.ng.$compileProvider.directive.input.number number} * - {@link angular.module.ng.$compileProvider.directive.input.email email} * - {@link angular.module.ng.$compileProvider.directive.input.url url} * - {@link angular.module.ng.$compileProvider.directive.select select} * - {@link angular.module.ng.$compileProvider.directive.textarea textarea} * */ var ngModelDirective = [function() { return { inject: { ngModel: 'accessor' }, require: ['ngModel', '^?form'], controller: NgModelController, link: function(scope, element, attr, ctrls) { // notify others, especially parent forms var modelCtrl = ctrls[0], formCtrl = ctrls[1] || nullFormCtrl; formCtrl.$addControl(modelCtrl); element.bind('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngChange * @restrict E * * @description * Evaluate given expression when user changes the input. * The expression is not evaluated when the value change is coming from the model. * * Note, this directive requires `ngModel` to be present. * * @element input * * @example * <doc:example> * <doc:source> * <script> * function Controller($scope) { * $scope.counter = 0; * $scope.change = function() { * $scope.counter++; * }; * } * </script> * <div ng-controller="Controller"> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> * <label for="ng-change-example2">Confirmed</label><br /> * debug = {{confirmed}}<br /> * counter = {{counter}} * </div> * </doc:source> * <doc:scenario> * it('should evaluate the expression if changing from view', function() { * expect(binding('counter')).toEqual('0'); * element('#ng-change-example1').click(); * expect(binding('counter')).toEqual('1'); * expect(binding('confirmed')).toEqual('true'); * }); * * it('should not evaluate the expression if changing from model', function() { * element('#ng-change-example2').click(); * expect(binding('counter')).toEqual('0'); * expect(binding('confirmed')).toEqual('true'); * }); * </doc:scenario> * </doc:example> */ var ngChangeDirective = valueFn({ require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); var requiredDirective = [function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var validator = function(value) { if (attr.required && (isEmpty(value) || value === false)) { ctrl.$setValidity('required', false); return; } else { ctrl.$setValidity('required', true); return value; } }; ctrl.$formatters.push(validator); ctrl.$parsers.unshift(validator); attr.$observe('required', function() { validator(ctrl.$viewValue); }); } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngList * * @description * Text input that converts between comma-seperated string into an array of strings. * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. If * specified in form `/something/` then the value will be converted into a regular expression. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.names = ['igor', 'misko', 'vojta']; } </script> <form name="myForm" ng-controller="Ctrl"> List: <input name="namesInput" ng-model="names" ng-list required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <tt>names = {{names}}</tt><br/> <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('names')).toEqual('["igor","misko","vojta"]'); expect(binding('myForm.namesInput.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('names').enter(''); expect(binding('names')).toEqual('[]'); expect(binding('myForm.namesInput.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var ngListDirective = function() { return { require: 'ngModel', link: function(scope, element, attr, ctrl) { var match = /\/(.*)\//.exec(attr.ngList), separator = match && new RegExp(match[1]) || attr.ngList || ','; var parse = function(viewValue) { var list = []; if (viewValue) { forEach(viewValue.split(separator), function(value) { if (value) list.push(trim(value)); }); } return list; }; ctrl.$parsers.push(parse); ctrl.$formatters.push(function(value) { if (isArray(value) && !equals(parse(ctrl.$viewValue), value)) { return value.join(', '); } return undefined; }); } }; }; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; var ngValueDirective = [function() { return { priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { return function(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { return function(scope, elm, attr) { attr.$$observers.value = []; scope.$watch(attr.ngValue, function(value) { attr.$set('value', value, false); }); }; } } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngBind * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * * Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when * it's desirable to put bindings into template that is momentarily displayed by the browser in its * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the * bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link angular.module.ng.$compileProvider.directive.ngCloak ngCloak} directive. * * * @element ANY * @param {expression} ngBind {@link guide/dev_guide.expressions Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.name = 'Whirled'; } </script> <div ng-controller="Ctrl"> Enter name: <input type="text" ng-model="name"><br> Hello <span ng-bind="name"></span>! </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ var ngBindDirective = ngDirective(function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBind); scope.$watch(attr.ngBind, function(value) { element.text(value == undefined ? '' : value); }); }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element * text should be replaced with the template in ngBindTemplate. * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few.) * * @element ANY * @param {string} ngBindTemplate template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.salutation = 'Hello'; $scope.name = 'World'; } </script> <div ng-controller="Ctrl"> Salutation: <input type="text" ng-model="salutation"><br> Name: <input type="text" ng-model="name"><br> <pre ng-bind-template="{{salutation}} {{name}}!"></pre> </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('salutation')). toBe('Hello'); expect(using('.doc-example-live').binding('name')). toBe('World'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('salutation')). toBe('Greetings'); expect(using('.doc-example-live').binding('name')). toBe('user'); }); </doc:scenario> </doc:example> */ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { return function(scope, element, attr) { // TODO: move this to scenario runner var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); element.addClass('ng-binding').data('$binding', interpolateFn); attr.$observe('ngBindTemplate', function(value) { element.text(value); }); } }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngBindHtmlUnsafe * * @description * Creates a binding that will innerHTML the result of evaluating the `expression` into the current * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if * {@link angular.module.ngSanitize.directive.ngBindHtml ngBindHtml} directive is too * restrictive and when you absolutely trust the source of the content you are binding to. * * See {@link angular.module.ngSanitize.$sanitize $sanitize} docs for examples. * * @element ANY * @param {expression} ngBindHtmlUnsafe {@link guide/dev_guide.expressions Expression} to evaluate. */ var ngBindHtmlUnsafeDirective = [function() { return function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe); scope.$watch(attr.ngBindHtmlUnsafe, function(value) { element.html(value || ''); }); }; }]; function classDirective(name, selector) { name = 'ngClass' + name; return ngDirective(function(scope, element, attr) { scope.$watch(attr[name], function(newVal, oldVal) { if (selector === true || scope.$index % 2 === selector) { if (oldVal && (newVal !== oldVal)) { if (isObject(oldVal) && !isArray(oldVal)) oldVal = map(oldVal, function(v, k) { if (v) return k }); element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal); } if (isObject(newVal) && !isArray(newVal)) newVal = map(newVal, function(v, k) { if (v) return k }); if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); } }, true); }); } /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngClass * * @description * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an * expression that represents all classes to be added. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the classes * new classes are added. * * @element ANY * @param {expression} ngClass {@link guide/dev_guide.expressions Expression} to eval. The result * of the evaluation can be a string representing space delimited class * names, an array, or a map of class names to boolean values. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myVar='my-class'"> <input type="button" value="clear" ng-click="myVar=''"> <br> <span ng-class="myVar">Sample Text</span> </file> <file name="style.css"> .my-class { color: red; } </file> <file name="scenario.js"> it('should check ng-class', function() { expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').prop('className')). toMatch(/my-class/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); }); </file> </example> */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngClassOdd * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link angular.module.ng.$compileProvider.directive.ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link angular.module.ng.$compileProvider.directive.ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassOdd {@link guide/dev_guide.expressions Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngClassEven * * @description * The `ngClassOdd` and `ngClassEven` works exactly as * {@link angular.module.ng.$compileProvider.directive.ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link angular.module.ng.$compileProvider.directive.ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassEven {@link guide/dev_guide.expressions Expression} to eval. The * result of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngCloak * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but typically a fine-grained application is * prefered in order to benefit from progressive rendering of the browser view. * * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and * `angular.min.js` files. Following is the css rule: * * <pre> * [ng\:cloak], [ng-cloak], .ng-cloak { * display: none; * } * </pre> * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive * during the compilation of the template it deletes the `ngCloak` element attribute, which * makes the compiled element visible. * * For the best result, `angular.js` script must be loaded in the head section of the html file; * alternatively, the css rule (above) must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ngCloak` in addition to `ngCloak` directive as shown in the example below. * * @element ANY * * @example <doc:example> <doc:source> <div id="template1" ng-cloak>{{ 'hello' }}</div> <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> </doc:source> <doc:scenario> it('should remove the template directive and css class', function() { expect(element('.doc-example-live #template1').attr('ng-cloak')). not().toBeDefined(); expect(element('.doc-example-live #template2').attr('ng-cloak')). not().toBeDefined(); }); </doc:scenario> </doc:example> * */ var ngCloakDirective = ngDirective({ compile: function(element, attr) { attr.$set('ngCloak', undefined); element.removeClass('ng-cloak'); } }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngController * * @description * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ngController` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the `{@link angular.module.ng.$route}` * service. * * @element ANY * @scope * @param {expression} ngController Name of a globally accessible constructor function or an * {@link guide/dev_guide.expressions expression} that on the current scope evaluates to a * constructor function. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. <doc:example> <doc:source> <script> function SettingsController($scope) { $scope.name = "John Smith"; $scope.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'[email protected]'} ]; $scope.greet = function() { alert(this.name); }; $scope.addContact = function() { this.contacts.push({type:'email', value:'[email protected]'}); }; $scope.removeContact = function(contactToRemove) { var index = this.contacts.indexOf(contactToRemove); this.contacts.splice(index, 1); }; $scope.clearContact = function(contact) { contact.type = 'phone'; contact.value = ''; }; } </script> <div ng-controller="SettingsController"> Name: <input type="text" ng-model="name"/> [ <a href="" ng-click="greet()">greet</a> ]<br/> Contact: <ul> <li ng-repeat="contact in contacts"> <select ng-model="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" ng-model="contact.value"/> [ <a href="" ng-click="clearContact(contact)">clear</a> | <a href="" ng-click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng-click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function() { expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li:nth-child(1) input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li:nth-child(2) input').val()) .toBe('[email protected]'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li:nth-child(3) input').val()) .toBe('[email protected]'); }); </doc:scenario> </doc:example> */ var ngControllerDirective = [function() { return { scope: true, controller: '@' }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngCsp * @priority 1000 * * @description * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. * This directive should be used on the root element of the application (typically the `<html>` * element or other element with the {@link angular.module.ng.$compileProvider.directive.ngApp ngApp} * directive). * * If enabled the performance of template expression evaluator will suffer slightly, so don't enable * this mode unless you need it. * * @element html */ var ngCspDirective = ['$sniffer', function($sniffer) { return { priority: 1000, compile: function() { $sniffer.csp = true; } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngClick * * @description * The ngClick allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} ngClick {@link guide/dev_guide.expressions Expression} to evaluate upon * click. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng-click', function() { expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. */ var ngEventDirectives = {}; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return function(scope, element, attr) { var fn = $parse(attr[directiveName]); element.bind(lowercase(name), function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }); }; }]; } ); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on dblclick event. * * @element ANY * @param {expression} ngDblclick {@link guide/dev_guide.expressions Expression} to evaluate upon * dblclick. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @param {expression} ngMousedown {@link guide/dev_guide.expressions Expression} to evaluate upon * mousedown. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @param {expression} ngMouseup {@link guide/dev_guide.expressions Expression} to evaluate upon * mouseup. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @param {expression} ngMouseover {@link guide/dev_guide.expressions Expression} to evaluate upon * mouseover. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @param {expression} ngMouseenter {@link guide/dev_guide.expressions Expression} to evaluate upon * mouseenter. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @param {expression} ngMouseleave {@link guide/dev_guide.expressions Expression} to evaluate upon * mouseleave. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @param {expression} ngMousemove {@link guide/dev_guide.expressions Expression} to evaluate upon * mousemove. (Event object is available as `$event`) * * @example * See {@link angular.module.ng.$compileProvider.directive.ngClick ngClick} */ /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} ngSubmit {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if (this.text) { this.list.push(this.text); this.text = ''; } }; } </script> <form ng-submit="submit()" ng-controller="Ctrl"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </doc:source> <doc:scenario> it('should check ng-submit', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); expect(input('text').val()).toBe(''); }); it('should ignore empty strings', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); }); </doc:scenario> </doc:example> */ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { element.bind('submit', function() { scope.$apply(attrs.ngSubmit); }); }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ngInclude won't work for cross-domain requests on all browsers and for * file:// access on some browsers). * * @scope * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link angular.module.ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example <example> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt>{{template.url}}</tt> <hr/> <div ng-include src="template.url"></div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.templates = [ { name: 'template1.html', url: 'template1.html'} , { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; } </file> <file name="template1.html"> Content of template1.html </file> <file name="template2.html"> Content of template2.html </file> <file name="scenario.js"> it('should load template1.html', function() { expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template1.html/); }); it('should load template2.html', function() { select('template').option('1'); expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template2.html/); }); it('should change to blank', function() { select('template').option(''); expect(element('.doc-example-live [ng-include]').text()).toEqual(''); }); </file> </example> */ /** * @ngdoc event * @name angular.module.ng.$compileProvider.directive.ngInclude#$includeContentLoaded * @eventOf angular.module.ng.$compileProvider.directive.ngInclude * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. */ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', function($http, $templateCache, $anchorScroll, $compile) { return { restrict: 'ECA', terminal: true, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; return function(scope, element) { var changeCounter = 0, childScope; var clearContent = function() { if (childScope) { childScope.$destroy(); childScope = null; } element.html(''); }; scope.$watch(srcExp, function(src) { var thisChangeId = ++changeCounter; if (src) { $http.get(src, {cache: $templateCache}).success(function(response) { if (thisChangeId !== changeCounter) return; if (childScope) childScope.$destroy(); childScope = scope.$new(); element.html(response); $compile(element.contents())(childScope); if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } childScope.$emit('$includeContentLoaded'); scope.$eval(onloadExp); }).error(function() { if (thisChangeId === changeCounter) clearContent(); }); } else clearContent(); }); }; } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngInit * * @description * The `ngInit` directive specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} ngInit {@link guide/dev_guide.expressions Expression} to eval. * * @example <doc:example> <doc:source> <div ng-init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function() { expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ var ngInitDirective = ngDirective({ compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } } } }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngNonBindable * @priority 1000 * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML. * * @element ANY * * @example * In this example there are two location where a simple binding (`{{}}`) is present, but the one * wrapped in `ngNonBindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng-non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng-non-bindable', function() { expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngPluralize * @restrict EA * * @description * # Overview * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js and the rules can be overridden * (see {@link guide/dev_guide.i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} in Angular's default en-US locale: "one" and "other". * * While a pural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. You will see the use of plural categories * and explicit number rules throughout later parts of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/dev_guide.expressions * Angular expression}; these are evaluated on the current scope for its binded value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object so that Angular * can interpret it correctly. * * The following example shows how to configure ngPluralize: * * <pre> * <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng-pluralize> *</pre> * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng-non-bindable>{{numberExpression}}</span>. * * # Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * <pre> * <ng-pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng-pluralize> * </pre> * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bounded to. * @param {string} when The mapping between plural category to its correspoding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.person1 = 'Igor'; $scope.person2 = 'Misko'; $scope.personCount = 1; } </script> <div ng-controller="Ctrl"> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng-pluralize><br> <!--- Example with offset ---> With Offset(2): <ng-pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng-pluralize> </div> </doc:source> <doc:scenario> it('should show correct pluralized string', function() { expect(element('.doc-example-live ng-pluralize:first').text()). toBe('1 person is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor is viewing.'); using('.doc-example-live').input('personCount').enter('0'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('Nobody is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Nobody is viewing.'); using('.doc-example-live').input('personCount').enter('2'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('2 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor and Misko are viewing.'); using('.doc-example-live').input('personCount').enter('3'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('3 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and one other person are viewing.'); using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('4 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); }); it('should show data-binded names', function() { using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); using('.doc-example-live').input('person1').enter('Di'); using('.doc-example-live').input('person2').enter('Vojta'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Di, Vojta and 2 other people are viewing.'); }); </doc:scenario> </doc:example> */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp), whensExpFns = {}; forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, '{{' + numberExp + '-' + offset + '}}')); }); scope.$watch(function() { var value = parseFloat(scope.$eval(numberExp)); if (!isNaN(value)) { //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, //check it against pluralization rules in $locale service if (!whens[value]) value = $locale.pluralCat(value - offset); return whensExpFns[value](scope, element, true); } else { return ''; } }, function(newVal) { element.text(newVal); }); } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$first` – `{boolean}` – true if the repeated element is first in the iterator. * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator. * * `$last` – `{boolean}` – true if the repeated element is last in the iterator. * * * @element ANY * @scope * @priority 1000 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: <doc:example> <doc:source> <div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng-repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </doc:source> <doc:scenario> it('should check ng-repeat', function() { var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); </doc:scenario> </doc:example> */ var ngRepeatDirective = ngDirective({ transclude: 'element', priority: 1000, terminal: true, compile: function(element, attr, linker) { return function(scope, iterStartElement, attr){ var expression = attr.ngRepeat; var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + lhs + "'."); } valueIdent = match[3] || match[1]; keyIdent = match[2]; // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is an array of objects with following properties. // - scope: bound scope // - element: previous element. // - index: position // We need an array of these objects since the same object can be returned from the iterator. // We expect this to be a rare case. var lastOrder = new HashQueueMap(); scope.$watch(function(scope){ var index, length, collection = scope.$eval(rhs), collectionLength = size(collection, true), childScope, // Same as lastOrder but it has the current state. It will become the // lastOrder on the next iteration. nextOrder = new HashQueueMap(), key, value, // key/value of iteration array, last, // last object information {scope, element, index} cursor = iterStartElement; // current position of the node if (!isArray(collection)) { // if object, extract keys, sort them and use to determine order of iteration over obj props array = []; for(key in collection) { if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { array.push(key); } } array.sort(); } else { array = collection || []; } // we are not using forEach for perf reasons (trying to avoid #call) for (index = 0, length = array.length; index < length; index++) { key = (collection === array) ? index : array[index]; value = collection[key]; last = lastOrder.shift(value); if (last) { // if we have already seen this object, then we need to reuse the // associated scope/element childScope = last.scope; nextOrder.push(value, last); if (index === last.index) { // do nothing cursor = last.element; } else { // existing item which got moved last.index = index; // This may be a noop, if the element is next, but I don't know of a good way to // figure this out, since it would require extra DOM access, so let's just hope that // the browsers realizes that it is noop, and treats it as such. cursor.after(last.element); cursor = last.element; } } else { // new item which we don't know about childScope = scope.$new(); } childScope[valueIdent] = value; if (keyIdent) childScope[keyIdent] = key; childScope.$index = index; childScope.$first = (index === 0); childScope.$last = (index === (collectionLength - 1)); childScope.$middle = !(childScope.$first || childScope.$last); if (!last) { linker(childScope, function(clone){ cursor.after(clone); last = { scope: childScope, element: (cursor = clone), index: index }; nextOrder.push(value, last); }); } } //shrink children for (key in lastOrder) { if (lastOrder.hasOwnProperty(key)) { array = lastOrder[key]; while(array.length) { value = array.pop(); value.element.remove(); value.scope.$destroy(); } } } lastOrder = nextOrder; }); }; } }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngShow * * @description * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) * conditionally. * * @element ANY * @param {expression} ngShow If the {@link guide/dev_guide.expressions expression} is truthy * then the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng-model="checked"><br/> Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/> Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span> </doc:source> <doc:scenario> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ //TODO(misko): refactor to remove element from the DOM var ngShowDirective = ngDirective(function(scope, element, attr){ scope.$watch(attr.ngShow, function(value){ element.css('display', toBoolean(value) ? '' : 'none'); }); }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngHide * * @description * The `ngHide` and `ngShow` directives hide or show a portion * of the HTML conditionally. * * @element ANY * @param {expression} ngHide If the {@link guide/dev_guide.expressions expression} truthy then * the element is shown or hidden respectively. * * @example <doc:example> <doc:source> Click me: <input type="checkbox" ng-model="checked"><br/> Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span> </doc:source> <doc:scenario> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </doc:scenario> </doc:example> */ //TODO(misko): refactor to remove element from the DOM var ngHideDirective = ngDirective(function(scope, element, attr){ scope.$watch(attr.ngHide, function(value){ element.css('display', toBoolean(value) ? 'none' : ''); }); }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngStyle * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} ngStyle {@link guide/dev_guide.expressions Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myStyle={color:'red'}"> <input type="button" value="clear" ng-click="myStyle={}"> <br/> <span ng-style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </file> <file name="style.css"> span { color: black; } </file> <file name="scenario.js"> it('should check ng-style', function() { expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </file> </example> */ var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watch(attr.ngStyle, function(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { forEach(oldStyles, function(val, style) { element.css(style, '');}); } if (newStyles) element.css(newStyles); }, true); }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngSwitch * @restrict EA * * @description * Conditionally change the DOM structure. * * @usageContent * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * ... * <ANY ng-switch-default>...</ANY> * * @scope * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * @paramDescription * On child elments add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. * * `ngSwitchDefault`: the default case when no other casses match. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; } </script> <div ng-controller="Ctrl"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div ng-switch on="selection" > <div ng-switch-when="settings">Settings Div</div> <span ng-switch-when="home">Home Span</span> <span ng-switch-default>default</span> </div> </div> </doc:source> <doc:scenario> it('should start in settings', function() { expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); }); it('should change to home', function() { select('selection').option('home'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); }); it('should select deafault', function() { select('selection').option('other'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); }); </doc:scenario> </doc:example> */ var NG_SWITCH = 'ng-switch'; var ngSwitchDirective = valueFn({ restrict: 'EA', compile: function(element, attr) { var watchExpr = attr.ngSwitch || attr.on, cases = {}; element.data(NG_SWITCH, cases); return function(scope, element){ var selectedTransclude, selectedElement, selectedScope; scope.$watch(watchExpr, function(value) { if (selectedElement) { selectedScope.$destroy(); selectedElement.remove(); selectedElement = selectedScope = null; } if ((selectedTransclude = cases['!' + value] || cases['?'])) { scope.$eval(attr.change); selectedScope = scope.$new(); selectedTransclude(selectedScope, function(caseElement) { selectedElement = caseElement; element.append(caseElement); }); } }); }; } }); var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 500, compile: function(element, attrs, transclude) { var cases = element.inheritedData(NG_SWITCH); assertArg(cases); cases['!' + attrs.ngSwitchWhen] = transclude; } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 500, compile: function(element, attrs, transclude) { var cases = element.inheritedData(NG_SWITCH); assertArg(cases); cases['?'] = transclude; } }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngTransclude * * @description * Insert the transcluded DOM here. * * @element ANY * * @example <doc:example module="transclude"> <doc:source> <script> function Ctrl($scope) { $scope.title = 'Lorem Ipsum'; $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; } angular.module('transclude', []) .directive('pane', function(){ return { restrict: 'E', transclude: true, scope: 'isolate', locals: { title:'bind' }, template: '<div style="border: 1px solid black;">' + '<div style="background-color: gray">{{title}}</div>' + '<div ng-transclude></div>' + '</div>' }; }); </script> <div ng-controller="Ctrl"> <input ng-model="title"><br> <textarea ng-model="text"></textarea> <br/> <pane title="{{title}}">{{text}}</pane> </div> </doc:source> <doc:scenario> it('should have transcluded', function() { input('title').enter('TITLE'); input('text').enter('TEXT'); expect(binding('title')).toEqual('TITLE'); expect(binding('text')).toEqual('TEXT'); }); </doc:scenario> </doc:example> * */ var ngTranscludeDirective = ngDirective({ controller: ['$transclude', '$element', function($transclude, $element) { $transclude(function(clone) { $element.append(clone); }); }] }); /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link angular.module.ng.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * @scope * @example <example module="ngView"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.template = {{$route.current.template}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { template: 'book.html', controller: BookCntl }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { template: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name angular.module.ng.$compileProvider.directive.ngView#$viewContentLoaded * @eventOf angular.module.ng.$compileProvider.directive.ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile', '$controller', function($http, $templateCache, $route, $anchorScroll, $compile, $controller) { return { restrict: 'ECA', terminal: true, link: function(scope, element, attr) { var changeCounter = 0, lastScope, onloadExp = attr.onload || ''; scope.$on('$afterRouteChange', update); update(); function destroyLastScope() { if (lastScope) { lastScope.$destroy(); lastScope = null; } } function update() { var template = $route.current && $route.current.template, thisChangeId = ++changeCounter; function clearContent() { // ignore callback if another route change occured since if (thisChangeId === changeCounter) { element.html(''); destroyLastScope(); } } if (template) { $http.get(template, {cache: $templateCache}).success(function(response) { // ignore callback if another route change occured since if (thisChangeId === changeCounter) { element.html(response); destroyLastScope(); var link = $compile(element.contents()), current = $route.current, controller; lastScope = current.scope = scope.$new(); if (current.controller) { controller = $controller(current.controller, {$scope: lastScope}); element.contents().data('$ngControllerController', controller); } link(lastScope); lastScope.$emit('$viewContentLoaded'); lastScope.$eval(onloadExp); // $anchorScroll might listen on event... $anchorScroll(); } }).error(clearContent); } else { clearContent(); } } } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.script * * @description * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the * template can be used by `ngInclude`, `ngView` or directive templates. * * @restrict E * @param {'text/ng-template'} type must be set to `'text/ng-template'` * * @example <doc:example> <doc:source> <script type="text/ng-template" id="/tpl.html"> Content of the template. </script> <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <div id="tpl-content" ng-include src="currentTpl"></div> </doc:source> <doc:scenario> it('should load template defined inside script tag', function() { element('#tpl-link').click(); expect(element('#tpl-content').text()).toMatch(/Content of the template/); }); </doc:scenario> </doc:example> */ var scriptDirective = ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element, attr) { if (attr.type == 'text/ng-template') { var templateUrl = attr.id, // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent text = element[0].text; $templateCache.put(templateUrl, text); } } }; }]; /** * @ngdoc directive * @name angular.module.ng.$compileProvider.directive.select * @restrict E * * @description * HTML `SELECT` element with angular data-binding. * * # `ngOptions` * * Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>` * elements for a `<select>` element using an array or an object obtained by evaluating the * `ngOptions` expression. *˝˝ * When an item in the select menu is select, the value of array element or object property * represented by the selected option will be bound to the model identified by the `ngModel` * directive of the parent select element. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent `null` or "not selected" * option. See example below for demonstration. * * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead * of {@link angular.module.ng.$compileProvider.directive.ngRepeat ngRepeat} when you want the * `select` model to be bound to a non-string value. This is because an option element can currently * be bound to string values only. * * @param {string} name assignable expression to data-bind to. * @param {string=} required The control is considered valid only if value is entered. * @param {comprehension_expression=} ngOptions in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * @example <doc:example> <doc:source> <script> function MyCntrl($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; $scope.color = $scope.colors[2]; // red } </script> <div ng-controller="MyCntrl"> <ul> <li ng-repeat="color in colors"> Name: <input ng-model="color.name"> [<a href ng-click="colors.splice($index, 1)">X</a>] </li> <li> [<a href ng-click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng-model="color" ng-options="c.name for c in colors"></select><br> Color (null allowed): <span class="nullable"> <select ng-model="color" ng-options="c.name for c in colors"> <option value="">-- chose color --</option> </select> </span><br/> Color grouped by shade: <select ng-model="color" ng-options="c.name group by c.shade for c in colors"> </select><br/> Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:color} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':color.name}"> </div> </div> </doc:source> <doc:scenario> it('should check ng-options', function() { expect(binding('{selected_color:color}')).toMatch('red'); select('color').option('0'); expect(binding('{selected_color:color}')).toMatch('black'); using('.nullable').select('color').option(''); expect(binding('{selected_color:color}')).toMatch('null'); }); </doc:scenario> </doc:example> */ var ngOptionsDirective = valueFn({ terminal: true }); var selectDirective = ['$compile', '$parse', function($compile, $parse) { //00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/, nullModelCtrl = {$setViewValue: noop}; return { restrict: 'E', require: ['select', '?ngModel'], controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { var self = this, optionsMap = {}, ngModelCtrl = nullModelCtrl, nullOption, unknownOption; self.databound = $attrs.ngModel; self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; } self.addOption = function(value) { optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { $element.val(value); if (unknownOption.parent()) unknownOption.remove(); } }; self.removeOption = function(value) { if (this.hasOption(value)) { delete optionsMap[value]; if (ngModelCtrl.$viewValue == value) { this.renderUnknownOption(value); } } }; self.renderUnknownOption = function(val) { var unknownVal = '? ' + hashKey(val) + ' ?'; unknownOption.val(unknownVal); $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE } self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); } $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed self.renderUnknownOption = noop; }); }], link: function(scope, element, attr, ctrls) { // if ngModel is not defined, we don't need to do anything if (!ctrls[1]) return; var selectCtrl = ctrls[0], ngModelCtrl = ctrls[1], multiple = attr.multiple, optionsExp = attr.ngOptions, nullOption = false, // if false, user will not be able to select it (used by ngOptions) emptyOption, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate =jqLite(document.createElement('optgroup')), unknownOption = optionTemplate.clone(); // find "null" option for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) { if (children[i].value == '') { emptyOption = nullOption = children.eq(i); break; } } selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator if (multiple && (attr.required || attr.ngRequired)) { var requiredValidator = function(value) { ngModelCtrl.$setValidity('required', !attr.required || (value && value.length)); return value; }; ngModelCtrl.$parsers.push(requiredValidator); ngModelCtrl.$formatters.unshift(requiredValidator); attr.$observe('required', function() { requiredValidator(ngModelCtrl.$viewValue); }); } if (optionsExp) Options(scope, element, ngModelCtrl); else if (multiple) Multiple(scope, element, ngModelCtrl); else Single(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// function Single(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; if (selectCtrl.hasOption(viewValue)) { if (unknownOption.parent()) unknownOption.remove(); selectElement.val(viewValue); if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy } else { if (isUndefined(viewValue) && emptyOption) { selectElement.val(''); } else { selectCtrl.renderUnknownOption(viewValue); } } }; selectElement.bind('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); }); }); } function Multiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); forEach(selectElement.children(), function(option) { option.selected = isDefined(items.get(option.value)); }); }; // we have to do it on each watch since ngModel watches reference, but // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function() { if (!equals(lastView, ctrl.$viewValue)) { lastView = copy(ctrl.$viewValue); ctrl.$render(); } }); selectElement.bind('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.children(), function(option) { if (option.selected) { array.push(option.value); } }); ctrl.$setViewValue(array); }); }); } function Options(scope, selectElement, ctrl) { var match; if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw Error( "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '" + optionsExp + "'."); } var displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]]; if (nullOption) { // compile the element since there might be bindings in it $compile(nullOption)(scope); // remove the class, which is added automatically because we recompile the element and it // becomes the compilation root nullOption.removeClass('ng-scope'); // we need to remove it before calling selectElement.html('') because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model selectElement.html(''); selectElement.bind('change', function() { scope.$apply(function() { var optionGroup, collection = valuesFn(scope) || [], locals = {}, key, value, optionElement, index, groupIndex, length, groupLength; if (multiple) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { key = optionElement.val(); if (keyName) locals[keyName] = key; locals[valueName] = collection[key]; value.push(valueFn(scope, locals)); } } } } else { key = selectElement.val(); if (key == '?') { value = undefined; } else if (key == ''){ value = null; } else { locals[valueName] = collection[key]; if (keyName) locals[keyName] = key; value = valueFn(scope, locals); } } ctrl.$setViewValue(value); }); }); ctrl.$render = render; // TODO(vojta): can't we optimize this ? scope.$watch(render); function render() { var optionGroups = {'':[]}, // Temporary location for the option groups before we render them optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, modelValue = ctrl.$modelValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, groupLength, length, groupIndex, index, locals = {}, selected, selectedSet = false, // nothing is selected yet lastElement, element; if (multiple) { selectedSet = new HashMap(modelValue); } else if (modelValue === null || nullOption) { // if we are not multiselect, and we are null then we have to add the nullOption optionGroups[''].push({selected:modelValue === null, id:'', label:''}); selectedSet = true; } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index]; optionGroupName = groupByFn(scope, locals) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (multiple) { selected = selectedSet.remove(valueFn(scope, locals)) != undefined; } else { selected = modelValue === valueFn(scope, locals); selectedSet = selectedSet || selected; // see if at least one item is selected } optionGroup.push({ id: keyName ? keys[index] : index, // either the index into array or key from object label: displayFn(scope, locals) || '', // what will be seen by the user selected: selected // determine if we should be selected }); } if (!multiple && !selectedSet) { // nothing was selected, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the beginning for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index+1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } if (existingOption.element.selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .attr('selected', option.selected) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } } } } }]; var optionDirective = ['$interpolate', function($interpolate) { var nullSelectCtrl = { addOption: noop, removeOption: noop }; return { restrict: 'E', priority: 100, require: '^select', compile: function(element, attr) { if (isUndefined(attr.value)) { var interpolateFn = $interpolate(element.text(), true); if (!interpolateFn) { attr.$set('value', element.text()); } } return function (scope, element, attr, selectCtrl) { if (selectCtrl.databound) { // For some reason Opera defaults to true and if not overridden this messes up the repeater. // We don't want the view to drive the initialization of the model anyway. element.prop('selected', false); } else { selectCtrl = nullSelectCtrl; } if (interpolateFn) { scope.$watch(interpolateFn, function(newVal, oldVal) { attr.$set('value', newVal); if (newVal !== oldVal) selectCtrl.removeOption(oldVal); selectCtrl.addOption(newVal); }); } else { selectCtrl.addOption(attr.value); } element.bind('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } } }]; var styleDirective = valueFn({ restrict: 'E', terminal: true }); /** * Setup file for the Scenario. * Must be first in the compilation/bootstrap list. */ // Public namespace angular.scenario = angular.scenario || {}; /** * Defines a new output format. * * @param {string} name the name of the new output format * @param {function()} fn function(context, runner) that generates the output */ angular.scenario.output = angular.scenario.output || function(name, fn) { angular.scenario.output[name] = fn; }; /** * Defines a new DSL statement. If your factory function returns a Future * it's returned, otherwise the result is assumed to be a map of functions * for chaining. Chained functions are subject to the same rules. * * Note: All functions on the chain are bound to the chain scope so values * set on "this" in your statement function are available in the chained * functions. * * @param {string} name The name of the statement * @param {function()} fn Factory function(), return a function for * the statement. */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) return result; var self = this; var chain = angular.extend({}, result); angular.forEach(chain, function(value, name) { if (angular.isFunction(value)) { chain[name] = function() { return executeStatement.call(self, value, arguments); }; } else { chain[name] = value; } }); return chain; } var statement = fn.apply(this, arguments); return function() { return executeStatement.call(this, statement, arguments); }; }; }; /** * Defines a new matcher for use with the expects() statement. The value * this.actual (like in Jasmine) is available in your matcher to compare * against. Your function should return a boolean. The future is automatically * created for you. * * @param {string} name The name of the matcher * @param {function()} fn The matching function(expected). */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { var prefix = 'expect ' + this.future.name + ' '; if (this.inverse) { prefix += 'not '; } var self = this; this.addFuture(prefix + name + ' ' + angular.toJson(expected), function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { error = 'expected ' + angular.toJson(expected) + ' but was ' + angular.toJson(self.actual); } done(error); }); }; }; /** * Initialize the scenario runner and run ! * * Access global window and document object * Access $runner through closure * * @param {Object=} config Config options */ angular.scenario.setUpAndRun = function(config) { var href = window.location.href; var body = _jQuery(document.body); var output = []; var objModel = new angular.scenario.ObjectModel($runner); if (config && config.scenario_output) { output = config.scenario_output.split(','); } angular.forEach(angular.scenario.output, function(fn, name) { if (!output.length || indexOf(output,name) != -1) { var context = body.append('<div></div>').find('div:last'); context.attr('id', name); fn.call({}, context, $runner, objModel); } }); if (!/^http/.test(href) && !/^https/.test(href)) { body.append('<p id="system-error"></p>'); body.find('#system-error').text( 'Scenario runner must be run using http or https. The protocol ' + href.split(':')[0] + ':// is not supported.' ); return; } var appFrame = body.append('<div id="application"></div>').find('#application'); var application = new angular.scenario.Application(appFrame); $runner.on('RunnerEnd', function() { appFrame.css('display', 'none'); appFrame.find('iframe').attr('src', 'about:blank'); }); $runner.on('RunnerError', function(error) { if (window.console) { console.log(formatException(error)); } else { // Do something for IE alert(error); } }); $runner.run(application); }; /** * Iterates through list with iterator function that must call the * continueFunction to continute iterating. * * @param {Array} list list to iterate over * @param {function()} iterator Callback function(value, continueFunction) * @param {function()} done Callback function(error, result) called when * iteration finishes or an error occurs. */ function asyncForEach(list, iterator, done) { var i = 0; function loop(error, index) { if (index && index > i) { i = index; } if (error || i >= list.length) { done(error); } else { try { iterator(list[i++], loop); } catch (e) { done(e); } } } loop(); } /** * Formats an exception into a string with the stack trace, but limits * to a specific line length. * * @param {Object} error The exception to format, can be anything throwable * @param {Number=} [maxStackLines=5] max lines of the stack trace to include * default is 5. */ function formatException(error, maxStackLines) { maxStackLines = maxStackLines || 5; var message = error.toString(); if (error.stack) { var stack = error.stack.split('\n'); if (stack[0].indexOf(message) === -1) { maxStackLines++; stack.unshift(error.message); } message = stack.slice(0, maxStackLines).join('\n'); } return message; } /** * Returns a function that gets the file name and line number from a * location in the stack if available based on the call site. * * Note: this returns another function because accessing .stack is very * expensive in Chrome. * * @param {Number} offset Number of stack lines to skip */ function callerFile(offset) { var error = new Error(); return function() { var line = (error.stack || '').split('\n')[offset]; // Clean up the stack trace line if (line) { if (line.indexOf('@') !== -1) { // Firefox line = line.substring(line.indexOf('@')+1); } else { // Chrome line = line.substring(line.indexOf('(')+1).replace(')', ''); } } return line || ''; }; } /** * Triggers a browser event. Attempts to choose the right event if one is * not specified. * * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement * @param {string} type Optional event type. * @param {Array.<string>=} keys Optional list of pressed keys * (valid values: 'alt', 'meta', 'shift', 'ctrl') */ function browserTrigger(element, type, keys) { if (element && !element.nodeName) element = element[0]; if (!element) return; if (!type) { type = { 'text': 'change', 'textarea': 'change', 'hidden': 'change', 'password': 'change', 'button': 'click', 'submit': 'click', 'reset': 'click', 'image': 'click', 'checkbox': 'click', 'radio': 'click', 'select-one': 'change', 'select-multiple': 'change' }[lowercase(element.type)] || 'click'; } if (lowercase(nodeName_(element)) == 'option') { element.parentNode.value = element.value; element = element.parentNode; type = 'change'; } keys = keys || []; function pressed(key) { return indexOf(keys, key) !== -1; } if (msie < 9) { switch(element.type) { case 'radio': case 'checkbox': element.checked = !element.checked; break; } // WTF!!! Error: Unspecified error. // Don't know why, but some elements when detached seem to be in inconsistent state and // calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error) // forcing the browser to compute the element position (by reading its CSS) // puts the element in consistent state. element.style.posLeft; // TODO(vojta): create event objects with pressed keys to get it working on IE<9 var ret = element.fireEvent('on' + type); if (lowercase(element.type) == 'submit') { while(element) { if (lowercase(element.nodeName) == 'form') { element.fireEvent('onsubmit'); break; } element = element.parentNode; } } return ret; } else { var evnt = document.createEvent('MouseEvents'), originalPreventDefault = evnt.preventDefault, iframe = _jQuery('#application iframe')[0], appWindow = iframe ? iframe.contentWindow : window, fakeProcessDefault = true, finalProcessDefault; // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208 appWindow.angular['ff-684208-preventDefault'] = false; evnt.preventDefault = function() { fakeProcessDefault = false; return originalPreventDefault.apply(evnt, arguments); }; evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'), pressed('shift'), pressed('meta'), 0, element); element.dispatchEvent(evnt); finalProcessDefault = !(appWindow.angular['ff-684208-preventDefault'] || !fakeProcessDefault); delete appWindow.angular['ff-684208-preventDefault']; return finalProcessDefault; } } /** * Don't use the jQuery trigger method since it works incorrectly. * * jQuery notifies listeners and then changes the state of a checkbox and * does not create a real browser event. A real click changes the state of * the checkbox and then notifies listeners. * * To work around this we instead use our own handler that fires a real event. */ (function(fn){ var parentTrigger = fn.trigger; fn.trigger = function(type) { if (/(click|change|keydown|blur|input)/.test(type)) { var processDefaults = []; this.each(function(index, node) { processDefaults.push(browserTrigger(node, type)); }); // this is not compatible with jQuery - we return an array of returned values, // so that scenario runner know whether JS code has preventDefault() of the event or not... return processDefaults; } return parentTrigger.apply(this, arguments); }; })(_jQuery.fn); /** * Finds all bindings with the substring match of name and returns an * array of their values. * * @param {string} bindExp The name to match * @return {Array.<string>} String of binding values */ _jQuery.fn.bindings = function(windowJquery, bindExp) { var result = [], match, bindSelector = '.ng-binding:visible'; if (angular.isString(bindExp)) { bindExp = bindExp.replace(/\s/g, ''); match = function (actualExp) { if (actualExp) { actualExp = actualExp.replace(/\s/g, ''); if (actualExp == bindExp) return true; if (actualExp.indexOf(bindExp) == 0) { return actualExp.charAt(bindExp.length) == '|'; } } } } else if (bindExp) { match = function(actualExp) { return actualExp && bindExp.exec(actualExp); } } else { match = function(actualExp) { return !!actualExp; }; } var selection = this.find(bindSelector); if (this.is(bindSelector)) { selection = selection.add(this); } function push(value) { if (value == undefined) { value = ''; } else if (typeof value != 'string') { value = angular.toJson(value); } result.push('' + value); } selection.each(function() { var element = windowJquery(this), binding; if (binding = element.data('$binding')) { if (typeof binding == 'string') { if (match(binding)) { push(element.scope().$eval(binding)); } } else { if (!angular.isArray(binding)) { binding = [binding]; } for(var fns, j=0, jj=binding.length; j<jj; j++) { fns = binding[j]; if (fns.parts) { fns = fns.parts; } else { fns = [fns]; } for (var scope, fn, i = 0, ii = fns.length; i < ii; i++) { if(match((fn = fns[i]).exp)) { push(fn(scope = scope || element.scope())); } } } } } }); return result; }; /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. * * @param {Object} context jQuery wrapper around HTML context. */ angular.scenario.Application = function(context) { this.context = context; context.append( '<h2>Current URL: <a href="about:blank">None</a></h2>' + '<div id="test-frames"></div>' ); }; /** * Gets the jQuery collection of frames. Don't use this directly because * frames may go stale. * * @private * @return {Object} jQuery collection */ angular.scenario.Application.prototype.getFrame_ = function() { return this.context.find('#test-frames iframe:last'); }; /** * Gets the window of the test runner frame. Always favor executeAction() * instead of this method since it prevents you from getting a stale window. * * @private * @return {Object} the window of the frame */ angular.scenario.Application.prototype.getWindow_ = function() { var contentWindow = this.getFrame_().prop('contentWindow'); if (!contentWindow) throw 'Frame window is not accessible.'; return contentWindow; }; /** * Changes the location of the frame. * * @param {string} url The URL. If it begins with a # then only the * hash of the page is changed. * @param {function()} loadFn function($window, $document) Called when frame loads. * @param {function()} errorFn function(error) Called if any error when loading. */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; var frame = this.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { errorFn('Sandbox Error: Navigating to about:blank is not allowed.'); } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); this.executeAction(loadFn); } else { frame.remove(); this.context.find('#test-frames').append('<iframe>'); frame = this.getFrame_(); frame.load(function() { frame.unbind(); try { self.executeAction(loadFn); } catch (e) { errorFn(e); } }).attr('src', url); } this.context.find('> h2 a').attr('href', url).text(url); }; /** * Executes a function in the context of the tested application. Will wait * for all pending angular xhr requests before executing. * * @param {function()} action The callback to execute. function($window, $document) * $document is a jQuery wrapped document. */ angular.scenario.Application.prototype.executeAction = function(action) { var self = this; var $window = this.getWindow_(); if (!$window.document) { throw 'Sandbox Error: Application document not accessible.'; } if (!$window.angular) { return action.call(this, $window, _jQuery($window.document)); } angularInit($window.document, function(element) { var $injector = $window.angular.element(element).injector(); var $element = _jQuery(element); $element.injector = function() { return $injector; }; $injector.invoke(function($browser){ $browser.notifyWhenNoOutstandingRequests(function() { action.call(self, $window, $element); }); }); }); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {function()} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * A future action in a spec. * * @param {string} name of the future action * @param {function()} future callback(error, result) * @param {function()} Optional. function that returns the file/line number. */ angular.scenario.Future = function(name, behavior, line) { this.name = name; this.behavior = behavior; this.fulfilled = false; this.value = undefined; this.parser = angular.identity; this.line = line || function() { return ''; }; }; /** * Executes the behavior of the closure. * * @param {function()} doneFn Callback function(error, result) */ angular.scenario.Future.prototype.execute = function(doneFn) { var self = this; this.behavior(function(error, result) { self.fulfilled = true; if (result) { try { result = self.parser(result); } catch(e) { error = e; } } self.value = error || result; doneFn(error, result); }); }; /** * Configures the future to convert it's final with a function fn(value) * * @param {function()} fn function(value) that returns the parsed value */ angular.scenario.Future.prototype.parsedWith = function(fn) { this.parser = fn; return this; }; /** * Configures the future to parse it's final value from JSON * into objects. */ angular.scenario.Future.prototype.fromJson = function() { return this.parsedWith(angular.fromJson); }; /** * Configures the future to convert it's final value from objects * into JSON. */ angular.scenario.Future.prototype.toJson = function() { return this.parsedWith(angular.toJson); }; /** * Maintains an object tree from the runner events. * * @param {Object} runner The scenario Runner instance to connect to. * * TODO(esprehn): Every output type creates one of these, but we probably * want one global shared instance. Need to handle events better too * so the HTML output doesn't need to do spec model.getSpec(spec.id) * silliness. * * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance */ angular.scenario.ObjectModel = function(runner) { var self = this; this.specMap = {}; this.listeners = []; this.value = { name: '', children: {} }; runner.on('SpecBegin', function(spec) { var block = self.value, definitions = []; angular.forEach(self.getDefinitionPath(spec), function(def) { if (!block.children[def.name]) { block.children[def.name] = { id: def.id, name: def.name, children: {}, specs: {} }; } block = block.children[def.name]; definitions.push(def.name); }); var it = self.specMap[spec.id] = block.specs[spec.name] = new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions); // forward the event self.emit('SpecBegin', it); }); runner.on('SpecError', function(spec, error) { var it = self.getSpec(spec.id); it.status = 'error'; it.error = error; // forward the event self.emit('SpecError', it, error); }); runner.on('SpecEnd', function(spec) { var it = self.getSpec(spec.id); complete(it); // forward the event self.emit('SpecEnd', it); }); runner.on('StepBegin', function(spec, step) { var it = self.getSpec(spec.id); var step = new angular.scenario.ObjectModel.Step(step.name); it.steps.push(step); // forward the event self.emit('StepBegin', it, step); }); runner.on('StepEnd', function(spec) { var it = self.getSpec(spec.id); var step = it.getLastStep(); if (step.name !== step.name) throw 'Events fired in the wrong order. Step names don\'t match.'; complete(step); // forward the event self.emit('StepEnd', it, step); }); runner.on('StepFailure', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('failure', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepFailure', it, modelStep, error); }); runner.on('StepError', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('error', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepError', it, modelStep, error); }); runner.on('RunnerEnd', function() { self.emit('RunnerEnd'); }); function complete(item) { item.endTime = new Date().getTime(); item.duration = item.endTime - item.startTime; item.status = item.status || 'success'; } }; /** * Adds a listener for an event. * * @param {string} eventName Name of the event to add a handler for * @param {function()} listener Function that will be called when event is fired */ angular.scenario.ObjectModel.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.ObjectModel.prototype.emit = function(eventName) { var self = this, args = Array.prototype.slice.call(arguments, 1), eventName = eventName.toLowerCase(); if (this.listeners[eventName]) { angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); } }; /** * Computes the path of definition describe blocks that wrap around * this spec. * * @param spec Spec to compute the path for. * @return {Array<Describe>} The describe block path */ angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) { var path = []; var currentDefinition = spec.definition; while (currentDefinition && currentDefinition.name) { path.unshift(currentDefinition); currentDefinition = currentDefinition.parent; } return path; }; /** * Gets a spec by id. * * @param {string} The id of the spec to get the object for. * @return {Object} the Spec instance */ angular.scenario.ObjectModel.prototype.getSpec = function(id) { return this.specMap[id]; }; /** * A single it block. * * @param {string} id Id of the spec * @param {string} name Name of the spec * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec */ angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) { this.id = id; this.name = name; this.startTime = new Date().getTime(); this.steps = []; this.fullDefinitionName = (definitionNames || []).join(' '); }; /** * Adds a new step to the Spec. * * @param {string} step Name of the step (really name of the future) * @return {Object} the added step */ angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) { var step = new angular.scenario.ObjectModel.Step(name); this.steps.push(step); return step; }; /** * Gets the most recent step. * * @return {Object} the step */ angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() { return this.steps[this.steps.length-1]; }; /** * Set status of the Spec from given Step * * @param {angular.scenario.ObjectModel.Step} step */ angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) { if (!this.status || step.status == 'error') { this.status = step.status; this.error = step.error; this.line = step.line; } }; /** * A single step inside a Spec. * * @param {string} step Name of the step */ angular.scenario.ObjectModel.Step = function(name) { this.name = name; this.startTime = new Date().getTime(); }; /** * Helper method for setting all error status related properties * * @param {string} status * @param {string} error * @param {string} line */ angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) { this.status = status; this.error = error; this.line = line; }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {function()} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * Runner for scenarios * * Has to be initialized before any test is loaded, * because it publishes the API into window (global space). */ angular.scenario.Runner = function($window) { this.listeners = []; this.$window = $window; this.rootDescribe = new angular.scenario.Describe(); this.currentDescribe = this.rootDescribe; this.api = { it: this.it, iit: this.iit, xit: angular.noop, describe: this.describe, ddescribe: this.ddescribe, xdescribe: angular.noop, beforeEach: this.beforeEach, afterEach: this.afterEach }; angular.forEach(this.api, angular.bind(this, function(fn, key) { this.$window[key] = angular.bind(this, fn); })); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.Runner.prototype.emit = function(eventName) { var self = this; var args = Array.prototype.slice.call(arguments, 1); eventName = eventName.toLowerCase(); if (!this.listeners[eventName]) return; angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); }; /** * Adds a listener for an event. * * @param {string} eventName The name of the event to add a handler for * @param {string} listener The fn(...) that takes the extra arguments from emit() */ angular.scenario.Runner.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Defines a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.describe = function(name, body) { var self = this; this.currentDescribe.describe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Same as describe, but makes ddescribe the only blocks to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.ddescribe = function(name, body) { var self = this; this.currentDescribe.ddescribe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Defines a test in a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.it = function(name, body) { this.currentDescribe.it(name, body); }; /** * Same as it, but makes iit tests the only tests to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.iit = function(name, body) { this.currentDescribe.iit(name, body); }; /** * Defines a function to be called before each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.beforeEach = function(body) { this.currentDescribe.beforeEach(body); }; /** * Defines a function to be called after each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.afterEach = function(body) { this.currentDescribe.afterEach(body); }; /** * Creates a new spec runner. * * @private * @param {Object} scope parent scope */ angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { var child = scope.$new(); var Cls = angular.scenario.SpecRunner; // Export all the methods to child scope manually as now we don't mess controllers with scopes // TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current for (var name in Cls.prototype) child[name] = angular.bind(child, Cls.prototype[name]); Cls.call(child); return child; }; /** * Runs all the loaded tests with the specified runner class on the * provided application. * * @param {angular.scenario.Application} application App to remote control. */ angular.scenario.Runner.prototype.run = function(application) { var self = this; var $root = angular.injector(['ng']).get('$rootScope'); angular.extend($root, this); angular.forEach(angular.scenario.Runner.prototype, function(fn, name) { $root[name] = angular.bind(self, fn); }); $root.application = application; $root.emit('RunnerBegin'); asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) { var dslCache = {}; var runner = self.createSpecRunner_($root); angular.forEach(angular.scenario.dsl, function(fn, key) { dslCache[key] = fn.call($root); }); angular.forEach(angular.scenario.dsl, function(fn, key) { self.$window[key] = function() { var line = callerFile(3); var scope = runner.$new(); // Make the dsl accessible on the current chain scope.dsl = {}; angular.forEach(dslCache, function(fn, key) { scope.dsl[key] = function() { return dslCache[key].apply(scope, arguments); }; }); // Make these methods work on the current chain scope.addFuture = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFuture.apply(scope, arguments); }; scope.addFutureAction = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFutureAction.apply(scope, arguments); }; return scope.dsl[key].apply(scope, arguments); }; }); runner.run(spec, function() { runner.$destroy(); specDone.apply(this, arguments); }); }, function(error) { if (error) { self.emit('RunnerError', error); } self.emit('RunnerEnd'); }); }; /** * This class is the "this" of the it/beforeEach/afterEach method. * Responsibilities: * - "this" for it/beforeEach/afterEach * - keep state for single it/beforeEach/afterEach execution * - keep track of all of the futures to execute * - run single spec (execute each future) */ angular.scenario.SpecRunner = function() { this.futures = []; this.afterIndex = 0; }; /** * Executes a spec which is an it block with associated before/after functions * based on the describe nesting. * * @param {Object} spec A spec object * @param {function()} specDone function that is called when the spec finshes. Function(error, index) */ angular.scenario.SpecRunner.prototype.run = function(spec, specDone) { var self = this; this.spec = spec; this.emit('SpecBegin', spec); try { spec.before.call(this); spec.body.call(this); this.afterIndex = this.futures.length; spec.after.call(this); } catch (e) { this.emit('SpecError', spec, e); this.emit('SpecEnd', spec); specDone(); return; } var handleError = function(error, done) { if (self.error) { return done(); } self.error = true; done(null, self.afterIndex); }; asyncForEach( this.futures, function(future, futureDone) { self.step = future; self.emit('StepBegin', spec, future); try { future.execute(function(error) { if (error) { self.emit('StepFailure', spec, future, error); self.emit('StepEnd', spec, future); return handleError(error, futureDone); } self.emit('StepEnd', spec, future); self.$window.setTimeout(function() { futureDone(); }, 0); }); } catch (e) { self.emit('StepError', spec, future, e); self.emit('StepEnd', spec, future); handleError(e, futureDone); } }, function(e) { if (e) { self.emit('SpecError', spec, e); } self.emit('SpecEnd', spec); // Call done in a timeout so exceptions don't recursively // call this function self.$window.setTimeout(function() { specDone(); }, 0); } ); }; /** * Adds a new future action. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) { var future = new angular.scenario.Future(name, angular.bind(this, behavior), line); this.futures.push(future); return future; }; /** * Adds a new future action to be executed on the application window. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) { var self = this; var NG = /\[ng\\\:/; return this.addFuture(name, function(done) { this.application.executeAction(function($window, $document) { //TODO(esprehn): Refactor this so it doesn't need to be in here. $document.elements = function(selector) { var args = Array.prototype.slice.call(arguments, 1); selector = (self.selector || '') + ' ' + (selector || ''); selector = _jQuery.trim(selector) || '*'; angular.forEach(args, function(value, index) { selector = selector.replace('$' + (index + 1), value); }); var result = $document.find(selector); if (selector.match(NG)) { result = result.add(selector.replace(NG, '[ng-'), $document); } if (!result.length) { throw { type: 'selector', message: 'Selector ' + selector + ' did not match any elements.' }; } return result; }; try { behavior.call(self, $window, $document, done); } catch(e) { if (e.type && e.type === 'selector') { done(e.message); } else { throw e; } } }); }, line); }; /** * Shared DSL statements that are useful to all scenarios. */ /** * Usage: * pause() pauses until you call resume() in the console */ angular.scenario.dsl('pause', function() { return function() { return this.addFuture('pausing for you to resume', function(done) { this.emit('InteractivePause', this.spec, this.step); this.$window.resume = function() { done(); }; }); }; }); /** * Usage: * sleep(seconds) pauses the test for specified number of seconds */ angular.scenario.dsl('sleep', function() { return function(time) { return this.addFuture('sleep for ' + time + ' seconds', function(done) { this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000); }); }; }); /** * Usage: * browser().navigateTo(url) Loads the url into the frame * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to * browser().reload() refresh the page (reload the same URL) * browser().window.href() window.location.href * browser().window.path() window.location.pathname * browser().window.search() window.location.search * browser().window.hash() window.location.hash without # prefix * browser().location().url() see angular.module.ng.$location#url * browser().location().path() see angular.module.ng.$location#path * browser().location().search() see angular.module.ng.$location#search * browser().location().hash() see angular.module.ng.$location#hash */ angular.scenario.dsl('browser', function() { var chain = {}; chain.navigateTo = function(url, delegate) { var application = this.application; return this.addFuture("browser navigate to '" + url + "'", function(done) { if (delegate) { url = delegate.call(this, url); } application.navigateTo(url, function() { done(null, url); }, done); }); }; chain.reload = function() { var application = this.application; return this.addFutureAction('browser reload', function($window, $document, done) { var href = $window.location.href; application.navigateTo(href, function() { done(null, href); }, done); }); }; chain.window = function() { var api = {}; api.href = function() { return this.addFutureAction('window.location.href', function($window, $document, done) { done(null, $window.location.href); }); }; api.path = function() { return this.addFutureAction('window.location.path', function($window, $document, done) { done(null, $window.location.pathname); }); }; api.search = function() { return this.addFutureAction('window.location.search', function($window, $document, done) { done(null, $window.location.search); }); }; api.hash = function() { return this.addFutureAction('window.location.hash', function($window, $document, done) { done(null, $window.location.hash.replace('#', '')); }); }; return api; }; chain.location = function() { var api = {}; api.url = function() { return this.addFutureAction('$location.url()', function($window, $document, done) { done(null, $document.injector().get('$location').url()); }); }; api.path = function() { return this.addFutureAction('$location.path()', function($window, $document, done) { done(null, $document.injector().get('$location').path()); }); }; api.search = function() { return this.addFutureAction('$location.search()', function($window, $document, done) { done(null, $document.injector().get('$location').search()); }); }; api.hash = function() { return this.addFutureAction('$location.hash()', function($window, $document, done) { done(null, $document.injector().get('$location').hash()); }); }; return api; }; return function() { return chain; }; }); /** * Usage: * expect(future).{matcher} where matcher is one of the matchers defined * with angular.scenario.matcher * * ex. expect(binding("name")).toEqual("Elliott") */ angular.scenario.dsl('expect', function() { var chain = angular.extend({}, angular.scenario.matcher); chain.not = function() { this.inverse = true; return chain; }; return function(future) { this.future = future; return chain; }; }); /** * Usage: * using(selector, label) scopes the next DSL element selection * * ex. * using('#foo', "'Foo' text field").input('bar') */ angular.scenario.dsl('using', function() { return function(selector, label) { this.selector = _jQuery.trim((this.selector||'') + ' ' + selector); if (angular.isString(label) && label.length) { this.label = label + ' ( ' + this.selector + ' )'; } else { this.label = this.selector; } return this.dsl; }; }); /** * Usage: * binding(name) returns the value of the first matching binding */ angular.scenario.dsl('binding', function() { return function(name) { return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) { var values = $document.elements().bindings($window.angular.element, name); if (!values.length) { return done("Binding selector '" + name + "' did not match."); } done(null, values[0]); }); }; }); /** * Usage: * input(name).enter(value) enters value in input with specified name * input(name).check() checks checkbox * input(name).select(value) selects the radio button with specified name/value * input(name).val() returns the value of the input. */ angular.scenario.dsl('input', function() { var chain = {}; var supportInputEvent = 'oninput' in document.createElement('div'); chain.enter = function(value, event) { return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); input.val(value); input.trigger(event || supportInputEvent && 'input' || 'change'); done(); }); }; chain.check = function() { return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox'); input.trigger('click'); done(); }); }; chain.select = function(value) { return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) { var input = $document. elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio'); input.trigger('click'); done(); }); }; chain.val = function() { return this.addFutureAction("return input val", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); done(null,input.val()); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * repeater('#products table', 'Product List').count() number of rows * repeater('#products table', 'Product List').row(1) all bindings in row as an array * repeater('#products table', 'Product List').column('product.name') all values across all rows in an array */ angular.scenario.dsl('repeater', function() { var chain = {}; chain.count = function() { return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.column = function(binding) { return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) { done(null, $document.elements().bindings($window.angular.element, binding)); }); }; chain.row = function(index) { return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) { var matches = $document.elements().slice(index, index + 1); if (!matches.length) return done('row ' + index + ' out of bounds'); done(null, matches.bindings($window.angular.element)); }); }; return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Usage: * select(name).option('value') select one option * select(name).options('value1', 'value2', ...) select options from a multi select */ angular.scenario.dsl('select', function() { var chain = {}; chain.option = function(value) { return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) { var select = $document.elements('select[ng\\:model="$1"]', this.name); var option = select.find('option[value="' + value + '"]'); if (option.length) { select.val(value); } else { option = select.find('option:contains("' + value + '")'); if (option.length) { select.val(option.val()); } } select.trigger('change'); done(); }); }; chain.options = function() { var values = arguments; return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) { var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name); select.val(values); select.trigger('change'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * element(selector, label).count() get the number of elements that match selector * element(selector, label).click() clicks an element * element(selector, label).query(fn) executes fn(selectedElements, done) * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr) * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr) */ angular.scenario.dsl('element', function() { var KEY_VALUE_METHODS = ['attr', 'css', 'prop']; var VALUE_METHODS = [ 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset' ]; var chain = {}; chain.count = function() { return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.click = function() { return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); var eventProcessDefault = elements.trigger('click')[0]; if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.query = function(fn) { return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) { fn.call(this, $document.elements(), done); }); }; angular.forEach(KEY_VALUE_METHODS, function(methodName) { chain[methodName] = function(name, value) { var args = arguments, futureName = (args.length == 1) ? "element '" + this.label + "' get " + methodName + " '" + name + "'" : "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); angular.forEach(VALUE_METHODS, function(methodName) { chain[methodName] = function(value) { var args = arguments, futureName = (args.length == 0) ? "element '" + this.label + "' " + methodName : futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Matchers for implementing specs. Follows the Jasmine spec conventions. */ angular.scenario.matcher('toEqual', function(expected) { return angular.equals(this.actual, expected); }); angular.scenario.matcher('toBe', function(expected) { return this.actual === expected; }); angular.scenario.matcher('toBeDefined', function() { return angular.isDefined(this.actual); }); angular.scenario.matcher('toBeTruthy', function() { return this.actual; }); angular.scenario.matcher('toBeFalsy', function() { return !this.actual; }); angular.scenario.matcher('toMatch', function(expected) { return new RegExp(expected).test(this.actual); }); angular.scenario.matcher('toBeNull', function() { return this.actual === null; }); angular.scenario.matcher('toContain', function(expected) { return includes(this.actual, expected); }); angular.scenario.matcher('toBeLessThan', function(expected) { return this.actual < expected; }); angular.scenario.matcher('toBeGreaterThan', function(expected) { return this.actual > expected; }); /** * User Interface for the Scenario Runner. * * TODO(esprehn): This should be refactored now that ObjectModel exists * to use angular bindings for the UI. */ angular.scenario.output('html', function(context, runner, model) { var specUiMap = {}, lastStepUiMap = {}; context.append( '<div id="header">' + ' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' + ' <ul id="status-legend" class="status-display">' + ' <li class="status-error">0 Errors</li>' + ' <li class="status-failure">0 Failures</li>' + ' <li class="status-success">0 Passed</li>' + ' </ul>' + '</div>' + '<div id="specs">' + ' <div class="test-children"></div>' + '</div>' ); runner.on('InteractivePause', function(spec) { var ui = lastStepUiMap[spec.id]; ui.find('.test-title'). html('paused... <a href="javascript:resume()">resume</a> when ready.'); }); runner.on('SpecBegin', function(spec) { var ui = findContext(spec); ui.find('> .tests').append( '<li class="status-pending test-it"></li>' ); ui = ui.find('> .tests li:last'); ui.append( '<div class="test-info">' + ' <p class="test-title">' + ' <span class="timer-result"></span>' + ' <span class="test-name"></span>' + ' </p>' + '</div>' + '<div class="scrollpane">' + ' <ol class="test-actions"></ol>' + '</div>' ); ui.find('> .test-info .test-name').text(spec.name); ui.find('> .test-info').click(function() { var scrollpane = ui.find('> .scrollpane'); var actions = scrollpane.find('> .test-actions'); var name = context.find('> .test-info .test-name'); if (actions.find(':visible').length) { actions.hide(); name.removeClass('open').addClass('closed'); } else { actions.show(); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); name.removeClass('closed').addClass('open'); } }); specUiMap[spec.id] = ui; }); runner.on('SpecError', function(spec, error) { var ui = specUiMap[spec.id]; ui.append('<pre></pre>'); ui.find('> pre').text(formatException(error)); }); runner.on('SpecEnd', function(spec) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); ui.removeClass('status-pending'); ui.addClass('status-' + spec.status); ui.find("> .test-info .timer-result").text(spec.duration + "ms"); if (spec.status === 'success') { ui.find('> .test-info .test-name').addClass('closed'); ui.find('> .scrollpane .test-actions').hide(); } updateTotals(spec.status); }); runner.on('StepBegin', function(spec, step) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>'); var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last'); stepUi.append( '<div class="timer-result"></div>' + '<div class="test-title"></div>' ); stepUi.find('> .test-title').text(step.name); var scrollpane = stepUi.parents('.scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); runner.on('StepFailure', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepError', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepEnd', function(spec, step) { var stepUi = lastStepUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); stepUi.find('.timer-result').text(step.duration + 'ms'); stepUi.removeClass('status-pending'); stepUi.addClass('status-' + step.status); var scrollpane = specUiMap[spec.id].find('> .scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); /** * Finds the context of a spec block defined by the passed definition. * * @param {Object} The definition created by the Describe object. */ function findContext(spec) { var currentContext = context.find('#specs'); angular.forEach(model.getDefinitionPath(spec), function(defn) { var id = 'describe-' + defn.id; if (!context.find('#' + id).length) { currentContext.find('> .test-children').append( '<div class="test-describe" id="' + id + '">' + ' <h2></h2>' + ' <div class="test-children"></div>' + ' <ul class="tests"></ul>' + '</div>' ); context.find('#' + id).find('> h2').text('describe: ' + defn.name); } currentContext = context.find('#' + id); }); return context.find('#describe-' + spec.definition.id); } /** * Updates the test counter for the status. * * @param {string} the status. */ function updateTotals(status) { var legend = context.find('#status-legend .status-' + status); var parts = legend.text().split(' '); var value = (parts[0] * 1) + 1; legend.text(value + ' ' + parts[1]); } /** * Add an error to a step. * * @param {Object} The JQuery wrapped context * @param {function()} fn() that should return the file/line number of the error * @param {Object} the error. */ function addError(context, line, error) { context.find('.test-title').append('<pre></pre>'); var message = _jQuery.trim(line() + '\n\n' + formatException(error)); context.find('.test-title pre:last').text(message); } }); /** * Generates JSON output into a context. */ angular.scenario.output('json', function(context, runner, model) { model.on('RunnerEnd', function() { context.text(angular.toJson(model.value)); }); }); /** * Generates XML output into a context. */ angular.scenario.output('xml', function(context, runner, model) { var $ = function(args) {return new context.init(args);}; model.on('RunnerEnd', function() { var scenario = $('<scenario></scenario>'); context.append(scenario); serializeXml(scenario, model.value); }); /** * Convert the tree into XML. * * @param {Object} context jQuery context to add the XML to. * @param {Object} tree node to serialize */ function serializeXml(context, tree) { angular.forEach(tree.children, function(child) { var describeContext = $('<describe></describe>'); describeContext.attr('id', child.id); describeContext.attr('name', child.name); context.append(describeContext); serializeXml(describeContext, child); }); var its = $('<its></its>'); context.append(its); angular.forEach(tree.specs, function(spec) { var it = $('<it></it>'); it.attr('id', spec.id); it.attr('name', spec.name); it.attr('duration', spec.duration); it.attr('status', spec.status); its.append(it); angular.forEach(spec.steps, function(step) { var stepContext = $('<step></step>'); stepContext.attr('name', step.name); stepContext.attr('duration', step.duration); stepContext.attr('status', step.status); it.append(stepContext); if (step.error) { var error = $('<error></error>'); stepContext.append(error); error.text(formatException(stepContext.error)); } }); }); } }); /** * Creates a global value $result with the result of the runner. */ angular.scenario.output('object', function(context, runner, model) { runner.$window.$result = model.value; }); bindJQuery(); publishExternalAPI(angular); var $runner = new angular.scenario.Runner(window), scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1], config = {}; angular.forEach(script.attributes, function(attr) { var match = attr.name.match(/ng[:\-](.*)/); if (match) { config[match[1]] = attr.value || true; } }); if (config.autotest) { JQLite(document).ready(function() { angular.scenario.setUpAndRun(config); }); } })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak {\n display: none;\n}\n\nng\\:form {\n display: block;\n}\n</style>'); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
stories/containers/channels/channels-header.stories.js
LN-Zap/zap-desktop
import React from 'react' import { storiesOf } from '@storybook/react' import ChannelsHeader from 'containers/Channels/ChannelsHeader' import { Provider } from '../../Provider' storiesOf('Containers.Channels', module) .addDecorator(story => <Provider story={story()} />) .addWithChapters('ChannelsHeader', { chapters: [ { sections: [ { sectionFn: () => <ChannelsHeader currentChannelCount={3} />, }, ], }, ], })
src/components/TextInput.js
hairmot/REACTModuleTest
import React from 'react'; import Quill from 'react-quill'; export default class TextInput extends React.Component { constructor(props) { super(props); this.state = {enlarged:'notEnlarged'}; } render() { var templateItem = this.props.inputsTemplate.find(a => a.fieldName === this.props.propertyname); var input = ''; var value = templateItem.formatting ? templateItem.formatting(this.props.value) : this.props.value; switch (templateItem.type) { case 'text': input = <input className="sv-form-control" type="text" onChange={this.props.update} name={this.props.propertyname} value={value} disabled={templateItem.readOnly ? 'disabled' : ''} /> break; case 'textarea': // input = <textArea style={{ resize: 'none' }} className="sv-form-control" onChange={this.props.update} name={this.props.propertyname} value={value}></textArea> input = <Quill value={value.replace(/¨/g, '"')} onChange={(val) => {this.props.update(null, val, this.props.propertyname)}} className=""/> break; case 'number': input = <input className="sv-form-control" type="number" onChange={this.props.update} name={this.props.propertyname} value={value} disabled={templateItem.readOnly ? 'disabled' : ''} /> break; case 'link': input = <a href={templateItem.formatting ? templateItem.formatting(this.props.value) : this.props.value} style={{ wordBreak: 'break-all' }}>{value}</a> break; case 'dropdown': input = <select className="sv-form-control"> { templateItem.validation.map(a => <option value={a}>{a}</option>) } </select> } return ( <div onFocus={() => templateItem.type === 'textarea' ? this.setState({enlarged:'enlarged'}) : ''} onBlur={() => templateItem.type === 'textarea' ? this.setState({enlarged:'notEnlarged'}) : ''} tabIndex={templateItem.type === 'textarea' ? '0' : '-1'} className={'sv-form-group sv-col-md-12 ' + this.state.enlarged}> <div className={this.props.biglabels ? 'sv-col-md-9' : 'sv-col-md-4'} > <label className="">{this.props.name}</label> </div> <div className={this.props.biglabels ? 'sv-col-md-3 ' : 'sv-col-md-8 ' + templateItem.type}> <div className="sv-input-group"> { input } { templateItem.type !== 'link' ? //value.toString().length >= (templateItem.minLength || 1) && value.toString().length <= (templateItem.maxLength || 9999)? templateItem.validate(value.toString(), templateItem.fieldName) ? <span className="sv-input-group-addon sv-alert-success" style={{ cursor: 'default' }}>✔</span> : <span className="sv-input-group-addon sv-alert-danger" style={{ cursor: 'default' }}>✘</span> : '' } </div> </div> </div > ) } }
Paths/React/05.Building Scalable React Apps/6-react-boilerplate-building-scalable-apps-m6-exercise-files/After/app/components/Navigation/index.js
phiratio/Pluralsight-materials
/** * * Navigation * */ import React from 'react'; import AppBar from '../AppBar'; import styles from './styles.css'; import Drawer from '../Drawer'; function Navigation({ topics, selectTopic, toggleDrawer, isDrawerOpen }) { return ( <div className={styles.navigation}> <AppBar toggleDrawer={toggleDrawer} /> <Drawer items={topics} selectItem={selectTopic} itemLabelAttr="name" itemKeyAttr="name" isDrawerOpen={isDrawerOpen} /> </div> ); } Navigation.propTypes = { topics: React.PropTypes.arrayOf( React.PropTypes.shape({ name: React.PropTypes.string.isRequired, description: React.PropTypes.string.isRequired, }) ).isRequired, selectTopic: React.PropTypes.func.isRequired, toggleDrawer: React.PropTypes.func.isRequired, isDrawerOpen: React.PropTypes.bool.isRequired, }; export default Navigation;
src/components/calendar.js
thipokKub/Clique-WebFront-Personnal
import React, { Component } from 'react'; import $ from 'jquery'; import './style/calendar.css'; Date.prototype.addDays = function(days) { var dat = new Date(this.valueOf()); dat.setDate(dat.getDate() + days); return dat; } Date.prototype.getMonthName = function(index) { const i = (!index) ? this.getMonth() : index; const month = ["January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; return month[i]; } Date.prototype.getMonthDays = function(index) { const year = this.getFullYear(); let FebDay = 28; if(year%4 === 0) { FebDay = 29; if(year%100 === 0) { FebDay = 28; if(year%400 === 0) { FebDay = 29; } } } const i = (!index) ? this.getMonth() : index; const dayOfMonth = [31, FebDay, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; return dayOfMonth[i]; } Date.prototype.getStartOfMonth = function() { let dat = new Date(this.valueOf()); dat.setDate(1); return dat; } Date.prototype.getPreviousMonth = function() { let dat = new Date(this.valueOf()); dat.setHours(0, 0, 0, 0); dat.setMonth( this.getMonth() -1 ); return dat; } Date.prototype.getNextMonth = function() { let dat = new Date(this.valueOf()); dat.setHours(0, 0, 0, 0); dat.setMonth( this.getMonth() + 1 ); return dat; } class EventBlob extends Component { constructor(props) { super(props); this.onStartMarquee = this.onStartMarquee.bind(this); this.onStopMarquee = this.onStopMarquee.bind(this); } onStartMarquee() { let containerWidth = this.refs.container.offsetWidth; let textWidth = this.refs.text.offsetWidth + 10; if(containerWidth < textWidth) { let scrollDistance = textWidth - containerWidth; let container = $(this.refs.container); let timeScroll = (scrollDistance >= 20) ? 2000 : (scrollDistance >= 10) ? 1000 : 500; container.stop(); container.animate({scrollLeft: scrollDistance}, timeScroll, 'linear'); } } onStopMarquee() { let container = $(this.refs.container); container.stop(); container.animate({scrollLeft: 0}, 'medium', 'swing'); } render() { return ( <div ref="container" className={`EventBlob ${ (this.props.color) ? this.props.color : '' }`} onMouseOver={this.onStartMarquee} onMouseLeave={this.onStopMarquee} > <span ref="text"> {this.props.name} </span> </div> ); } } class DayInfo extends Component { render() { let cn = 'DayInfo'; return ( <div className={cn} ref="DayInfo"> <div style={{'color': '#000', 'border': 'none', 'position': 'absolute', 'top': '10px', 'right': '10px'}}>{this.props.date}</div> <div className="Blob-Container"> {this.props.Events.map((item, index) => { return <EventBlob key={`${this.props.keyName}-${index}`} name={item.name} color={`color-${item.color}`}/>})} </div> </div> ); } } class Calendar extends Component { constructor(props) { super(props); this.state = { 'refDate': new Date().setHours(0, 0, 0, 0), 'DateState': [], 'events': [ { 'from': new Date("2017-06-10"), 'to': new Date("2017-06-20"), 'name': "Dream", 'eventId': '', 'color': 'blue', 'nudge': 0 }, { 'from': new Date("2017-06-11"), 'to': new Date("2017-06-15"), 'name': "Of", 'eventId': '', 'color': 'yellow', 'nudge': 1 }, { 'from': new Date("2017-06-30"), 'to': new Date("2017-07-02"), 'name': "La La La", 'eventId': '', 'color': 'green', 'nudge': 0 }, { 'from': new Date("2017-06-24"), 'to': new Date("2017-06-26"), 'name': "LOL", 'eventId': '', 'color': 'red', 'nudge': 0 }, { 'from': new Date("2017-06-11"), 'to': new Date("2017-06-14"), 'name': "LOL LOL LOL", 'eventId': '', 'color': 'pink', 'nudge': 2 }, { 'from': new Date("2017-06-21"), 'to': new Date("2017-06-21"), 'name': "more...", 'eventId': '', 'color': 'blue', 'nudge': 0 }, { 'from': new Date("2017-06-15"), 'to': new Date("2017-06-16"), 'name': "I spy with little eyes", 'eventId': '', 'color': 'red', 'nudge': 0 }, { 'from': new Date("2017-06-16"), 'to': new Date("2017-06-18"), 'name': "La La Land", 'eventId': '', 'color': 'pink', 'nudge': 0 } ] } this.onClickPrev = this.onClickPrev.bind(this); this.onClickNext = this.onClickNext.bind(this); this.setDateGrid = this.setDateGrid.bind(this); this.EventInDay = this.EventInDay.bind(this); this.onSetCalendar = this.onSetCalendar.bind(this); this.onDateClick = this.onDateClick.bind(this) } compareDate(day1, day2) { return (day1.getFullYear() === day2.getFullYear()) && (day1.getMonth() === day2.getMonth()) && (day1.getDate() === day2.getDate()); } onClickPrev() { this.onSetCalendar(new Date(this.state.refDate).getPreviousMonth()); } onClickNext() { this.onSetCalendar(new Date(this.state.refDate).getNextMonth()); } onSetNudge(dateStart, dateEnd, dateState) { //Assume dateStart and dateEnd is in the same month let i = 0; while(i < 3) { if(dateState[dateStart.getDate()-1][i]) { for(let tmp = dateStart.getDate()-1; tmp < dateEnd.getDate(); tmp++) { dateState[tmp][i] = false; } return i; } i++; } return i; } setDateGrid(dateStart, dateEnd, color, nudgeNo, name, DateState) { const startOfMonth = new Date(this.state.refDate).getStartOfMonth(); const SOMDay = startOfMonth.getDay(); const monthDay = startOfMonth.getMonthDays(); const thisMonth = new Date(this.state.refDate).getMonth(); //const nudge = (!nudgeNo) ? '' : ` Nudge-${nudgeNo}` let row = Math.floor( (SOMDay + dateStart.getDate() - 1)/7) + 1; let col = (SOMDay + dateStart.getDate() + 6)%7 + 1; let wRange = (dateEnd.getDate() - dateStart.getDate() + 1); if(dateStart.getMonth() === dateEnd.getMonth() && thisMonth === dateStart.getMonth()) { let nudgeNum = this.onSetNudge(dateStart, dateEnd, DateState); let nudge = `Nudge-${nudgeNum}`; if(nudgeNum >= 3) return null; if(!this.compareDate(dateStart, dateEnd) && (dateStart.getDay() >= dateEnd.getDay() || wRange >= 7)) { let content = []; let i = 1; content.push(<div key={`${0}-event`} className={`EventRange w-${7-dateStart.getDay()} pos-${row}-${col} color-${color} BuntEnd ${nudge}`}>{name}</div>); wRange -= 7-dateStart.getDay(); while(wRange > 7) { content.push(<div key={`${i}-event`} className={`EventRange w-${7} pos-${row + i}-${1} color-${color} BuntStart BuntEnd ${nudge}`}>{name}</div>); wRange -= 7; i++; } content.push(<div key={`${i}-event`} className={`EventRange w-${wRange} pos-${row + i}-${1} color-${color} BuntStart ${nudge}`}>{name}</div>); return (<div className="EventRange-Container">{content}</div>); } return (<div className="EventRange-Container"><div className={`EventRange w-${wRange} pos-${row}-${col} color-${color} ${nudge}`}>{name}</div></div>); } else if(dateStart.getMonth() < thisMonth && thisMonth < dateEnd.getMonth() ) { let content =[]; let i = 1; let nudgeNum = this.onSetNudge(startOfMonth, startOfMonth.addDays(monthDay-1), DateState); let nudge = `Nudge-${nudgeNum}`; if(nudgeNum >= 2) return null; content.push(<div key={`${0}-event`} className={`EventRange w-${7 - SOMDay} pos-${1}-${SOMDay + 1} color-${color} BuntStart BuntEnd ${nudge}`}>{name}</div>); wRange = monthDay - (7 - SOMDay); while(wRange > 7) { content.push(<div key={`${i}-event`} className={`EventRange w-${7} pos-${i+1}-${1} color-${color} BuntStart BuntEnd ${nudge}`}>{name}</div>) wRange -= 7; i++; } content.push(<div key={`${i}-event`} className={`EventRange w-${wRange} pos-${i+1}-${1} color-${color} BuntStart BuntEnd ${nudge}`}>{name}</div>); return (<div className="EventRange-Container">{content}</div>); } else if(dateStart.getMonth() !== dateEnd.getMonth()) { if(dateStart.getMonth() === thisMonth) { let nudgeNum = this.onSetNudge(dateStart, startOfMonth.addDays(monthDay-1), DateState); let nudge = `Nudge-${nudgeNum}`; if(nudgeNum >= 2) return null; if(row === Math.ceil((SOMDay + monthDay)/7)) { return (<div className="EventRange-Container"><div className={`EventRange w-${monthDay - dateStart.getDate() + 1} pos-${row}-${col} color-${color} BuntEnd ${nudge}`}>{name}</div></div>); } else { let content = []; let i = 1; wRange = monthDay - dateStart.getDate() + 1; content.push(<div key={`${0}-event`} className={`EventRange w-${7-dateStart.getDay()} pos-${row}-${col} color-${color} BuntEnd ${nudge}`}>{name}</div>); wRange -= 7-dateStart.getDay(); while(wRange > 7) { content.push(<div key={`${i}-event`} className={`EventRange w-${7} pos-${row + i}-${1} color-${color} BuntStart BuntEnd ${nudge}`}>{name}</div>) wRange -= 7; i++; } content.push(<div key={`${i}-event`} className={`EventRange w-${wRange} pos-${row + i}-${1} color-${color} BuntStart BuntEnd ${nudge}`}>{name}</div>); return (<div className="EventRange-Container">{content}</div>); } } else if(dateEnd.getMonth() === thisMonth) { let content = []; let i = 1; let nudgeNum = this.onSetNudge(startOfMonth, dateEnd, DateState); let nudge = `Nudge-${nudgeNum}`; if(nudgeNum >= 2) return null; wRange = dateEnd.getDate(); //Position of end date row = Math.floor( (SOMDay + dateEnd.getDate() - 1)/7) + 1; col = (SOMDay + dateEnd.getDate() + 6)%7 + 1; if(row === 1) { row = 1; col = SOMDay + 1; return (<div className="EventRange-Container"><div className={`EventRange w-${dateEnd.getDay() - SOMDay + 1} pos-${row}-${col} color-${color} BuntStart ${nudge}`}>{name}</div></div>); } else { content.push(<div key={`${0}-event`} className={`EventRange w-${7 - SOMDay} pos-${1}-${SOMDay + 1} color-${color} BuntStart BuntEnd ${nudge}`}>{name}</div>); wRange = dateEnd.getDate() - (7 - SOMDay); while(wRange > 7) { content.push(<div key={`${i}-event`} className={`EventRange w-${7} pos-${i+1}-${1} color-${color} BuntStart BuntEnd ${nudge}`}>{name}</div>) wRange -= 7; i++; } content.push(<div key={`${i}-event`} className={`EventRange w-${wRange} pos-${i+1}-${1} color-${color} BuntStart ${nudge}`}>{name}</div>) return (<div className="EventRange-Container">{content}</div>); } } } return null; } EventInDay(day) { return this.state.events.filter((item) => { if(this.compareDate(day, item.from)) return true; return (item.from.getTime() <= day.getTime() && day.getTime() <= item.to.getTime()) }); } onSetCalendar(refDate) { //When month is changed const startOfMonth = new Date(refDate).getStartOfMonth(); const monthDay = startOfMonth.getMonthDays(); let new_state = []; for(var i = 0; i < monthDay; i++) { new_state.push(false); } this.setState({ ...(this.state), 'DateState': new_state, 'refDate': refDate }); } componentWillMount() { this.onSetCalendar(new Date(this.state.refDate)); let sortedEvents = [...this.state.events]; sortedEvents = sortedEvents.sort((a, b) => { if(a.from < b.from) return -1; else if(a.from > b.from) return 1; return 0; }); this.setState({ ...(this.state), 'events': sortedEvents }); } onDateClick(date) { const startOfMonth = new Date(this.state.refDate).getStartOfMonth(); const monthDay = startOfMonth.getMonthDays(); if(date <= 0 || date > monthDay) return; let new_state = [...this.state.DateState]; if(new_state.indexOf(true) !== date-1) new_state[new_state.indexOf(true)] = false; new_state[date - 1] = !new_state[date - 1]; this.setState({ ...(this.state), 'DateState': new_state }) } render() { const refDate = new Date(this.state.refDate); const startOfMonth = new Date(this.state.refDate).getStartOfMonth(); const SOMDay = startOfMonth.getDay(); const monthDay = startOfMonth.getMonthDays(); const dayName = ["SUNDAY", "MONDAY", "TUESDAY", "WEDESDAY", "THURSDAY", "FRIDAY", "SATURDAY"]; let DateAvalible = []; for(let i = 0; i < monthDay; i++) { DateAvalible.push([true, true, true]); } const totalDayRendered = Math.ceil((SOMDay + monthDay)/7)*7; let dayRef = new Date(startOfMonth); let Days = []; for(let i = 0; i < totalDayRendered; i++) { let cn = "Day "; if(i >= SOMDay && i < (monthDay + SOMDay)) { if((i === SOMDay + refDate.getDate() - 1) && this.compareDate(refDate, new Date())) cn += "Today"; } else { cn += "Disabled"; } Days.push( <div className={cn} key={i+1} onClick={(e) => { if(e.target.className === "Day " || e.target.className === "DayInfo" || e.target.className === "Day Today" || e.target.className === "Blob-Container") { this.onDateClick(i - SOMDay + 1); } }}> {(i >= SOMDay && i < (monthDay + SOMDay)) ? (i - SOMDay + 1) : ''} {(i >= SOMDay && i < (monthDay + SOMDay) && this.state.DateState[i - SOMDay]) ? <DayInfo Events={this.EventInDay(new Date(dayRef))} key={`Date-${i - SOMDay + 1}`} keyName={`Date-${i - SOMDay + 1}`} date={i - SOMDay + 1} /> : null} {(this.EventInDay(new Date(dayRef)).length > 0) ? (<div style={{'position': 'absolute', 'bottom': '5px', 'left': '5px', 'fontSize': '0.75em', 'color': '#AAA'}}>{this.EventInDay(new Date(dayRef)).length}</div>) : null} </div>) if(i >= SOMDay && i < (monthDay + SOMDay)) dayRef = dayRef.addDays(1); } let CalendarBody = ( <div className="Body"> <div className="Week"> {dayName.map((item, index) => (<div key={`Day-${index}`} className="Day text-center">{item}</div>))} </div> <div className={`Days d-${Math.ceil((SOMDay + monthDay)/7)}`}> {Days} </div> {this.state.events.map((item) => { return (this.setDateGrid(item.from, item.to, item.color, item.nudge, item.name, DateAvalible)) })} </div> ); return ( <div className="Calendar-Container"> <div className="Calendar"> <div className="Head"> <button className="invisible square-round" onClick={this.onClickPrev}> <i className="fa fa-angle-left" aria-hidden="true"></i> </button> <span> {refDate.getMonthName().toUpperCase()} </span> <button className="invisible square-round" onClick={this.onClickNext}> <i className="fa fa-angle-right" aria-hidden="true"></i> </button> <div> {refDate.getFullYear()} </div> </div> {CalendarBody} </div> </div> ); } } export default Calendar;
client/test/containers/DraggableStickerContainer.spec.js
marlonbernardes/coding-stickers
import React from 'react'; import { expect } from 'chai'; import { List as ImmutableList, Map } from 'immutable'; import { shallow } from 'enzyme'; import { DraggableStickerContainer } from '../../src/containers/DraggableStickerContainer'; import DraggableSticker from '../../src/components/DraggableSticker'; describe('<DraggableStickerContainer />', () => { it('renders the draggable sticker', () => { const product = new Map({ widthInInches: 10, heightInInches: 20, }); const selectedStickers = ImmutableList.of(new Map({ index: 0, x: 10, y: 20, image: 'foo.png', })) const component = shallow(( <DraggableStickerContainer product={product} selectedStickers={selectedStickers} /> )); const html = component.html(); expect(html).to.contain('foo.png'); expect(html).to.contain('draggable-sticker'); }); });
ajax/libs/babel-core/5.5.0/browser-polyfill.js
terrymun/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (global){ "use strict"; require("core-js/shim"); require("regenerator/runtime"); if (global._babelPolyfill) { throw new Error("only one instance of babel/polyfill is allowed"); } global._babelPolyfill = true; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"core-js/shim":79,"regenerator/runtime":80}],2:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],3:[function(require,module,exports){ 'use strict'; // false -> Array#indexOf // true -> Array#includes var $ = require('./$'); module.exports = function(IS_INCLUDES){ return function(el /*, fromIndex = 0 */){ var O = $.toObject(this) , length = $.toLength(O.length) , index = $.toIndex(arguments[1], length) , value; if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index; } return !IS_INCLUDES && -1; }; }; },{"./$":22}],4:[function(require,module,exports){ 'use strict'; // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var $ = require('./$') , ctx = require('./$.ctx'); module.exports = function(TYPE){ var IS_MAP = TYPE == 1 , IS_FILTER = TYPE == 2 , IS_SOME = TYPE == 3 , IS_EVERY = TYPE == 4 , IS_FIND_INDEX = TYPE == 6 , NO_HOLES = TYPE == 5 || IS_FIND_INDEX; return function(callbackfn/*, that = undefined */){ var O = Object($.assertDefined(this)) , self = $.ES5Object(O) , f = ctx(callbackfn, arguments[1], 3) , length = $.toLength(self.length) , index = 0 , result = IS_MAP ? Array(length) : IS_FILTER ? [] : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; },{"./$":22,"./$.ctx":12}],5:[function(require,module,exports){ var $ = require('./$'); function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } assert.def = $.assertDefined; assert.fn = function(it){ if(!$.isFunction(it))throw TypeError(it + ' is not a function!'); return it; }; assert.obj = function(it){ if(!$.isObject(it))throw TypeError(it + ' is not an object!'); return it; }; assert.inst = function(it, Constructor, name){ if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!"); return it; }; module.exports = assert; },{"./$":22}],6:[function(require,module,exports){ var $ = require('./$') , enumKeys = require('./$.enum-keys'); // 19.1.2.1 Object.assign(target, source, ...) /* eslint-disable no-unused-vars */ module.exports = Object.assign || function assign(target, source){ /* eslint-enable no-unused-vars */ var T = Object($.assertDefined(target)) , l = arguments.length , i = 1; while(l > i){ var S = $.ES5Object(arguments[i++]) , keys = enumKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; }; },{"./$":22,"./$.enum-keys":14}],7:[function(require,module,exports){ var $ = require('./$') , TAG = require('./$.wks')('toStringTag') , toString = {}.toString; function cof(it){ return toString.call(it).slice(8, -1); } cof.classof = function(it){ var O, T; return it == undefined ? it === undefined ? 'Undefined' : 'Null' : typeof (T = (O = Object(it))[TAG]) == 'string' ? T : cof(O); }; cof.set = function(it, tag, stat){ if(it && !$.has(it = stat ? it : it.prototype, TAG))$.hide(it, TAG, tag); }; module.exports = cof; },{"./$":22,"./$.wks":33}],8:[function(require,module,exports){ 'use strict'; var $ = require('./$') , ctx = require('./$.ctx') , safe = require('./$.uid').safe , assert = require('./$.assert') , forOf = require('./$.for-of') , step = require('./$.iter').step , has = $.has , set = $.set , isObject = $.isObject , hide = $.hide , isFrozen = Object.isFrozen || $.core.Object.isFrozen , ID = safe('id') , O1 = safe('O1') , LAST = safe('last') , FIRST = safe('first') , ITER = safe('iter') , SIZE = $.DESC ? safe('size') : 'size' , id = 0; function fastKey(it, create){ // return primitive with prefix if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; // can't set id to frozen object if(isFrozen(it))return 'F'; if(!has(it, ID)){ // not necessary to add id if(!create)return 'E'; // add missing object id hide(it, ID, ++id); // return object id with prefix } return 'O' + it[ID]; } function getEntry(that, key){ // fast case var index = fastKey(key), entry; if(index != 'F')return that[O1][index]; // frozen object case for(entry = that[FIRST]; entry; entry = entry.n){ if(entry.k == key)return entry; } } module.exports = { getConstructor: function(NAME, IS_MAP, ADDER){ function C(){ var that = assert.inst(this, C, NAME) , iterable = arguments[0]; set(that, O1, $.create(null)); set(that, SIZE, 0); set(that, LAST, undefined); set(that, FIRST, undefined); if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); } $.mix(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear(){ for(var that = this, data = that[O1], entry = that[FIRST]; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that[FIRST] = that[LAST] = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that[O1][entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that[FIRST] == entry)that[FIRST] = next; if(that[LAST] == entry)that[LAST] = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments[1], 3) , entry; while(entry = entry ? entry.n : this[FIRST]){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key){ return !!getEntry(this, key); } }); if($.DESC)$.setDesc(C.prototype, 'size', { get: function(){ return assert.def(this[SIZE]); } }); return C; }, def: function(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry){ entry.v = value; // create new entry } else { that[LAST] = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that[LAST], // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that[FIRST])that[FIRST] = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index != 'F')that[O1][index] = entry; } return that; }, getEntry: getEntry, // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 setIter: function(C, NAME, IS_MAP){ require('./$.iter-define')(C, NAME, function(iterated, kind){ set(this, ITER, {o: iterated, k: kind}); }, function(){ var iter = this[ITER] , kind = iter.k , entry = iter.l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!iter.o || !(iter.l = entry = entry ? entry.n : iter.o[FIRST])){ // or finish the iteration iter.o = undefined; return step(1); } // return step by kind if(kind == 'keys' )return step(0, entry.k); if(kind == 'values')return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); } }; },{"./$":22,"./$.assert":5,"./$.ctx":12,"./$.for-of":15,"./$.iter":21,"./$.iter-define":19,"./$.uid":31}],9:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $def = require('./$.def') , forOf = require('./$.for-of'); module.exports = function(NAME){ $def($def.P, NAME, { toJSON: function toJSON(){ var arr = []; forOf(this, false, arr.push, arr); return arr; } }); }; },{"./$.def":13,"./$.for-of":15}],10:[function(require,module,exports){ 'use strict'; var $ = require('./$') , safe = require('./$.uid').safe , assert = require('./$.assert') , forOf = require('./$.for-of') , _has = $.has , isObject = $.isObject , hide = $.hide , isFrozen = Object.isFrozen || $.core.Object.isFrozen , id = 0 , ID = safe('id') , WEAK = safe('weak') , LEAK = safe('leak') , method = require('./$.array-methods') , find = method(5) , findIndex = method(6); function findFrozen(store, key){ return find.call(store.array, function(it){ return it[0] === key; }); } // fallback for frozen keys function leakStore(that){ return that[LEAK] || hide(that, LEAK, { array: [], get: function(key){ var entry = findFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findFrozen(this, key); }, set: function(key, value){ var entry = findFrozen(this, key); if(entry)entry[1] = value; else this.array.push([key, value]); }, 'delete': function(key){ var index = findIndex.call(this.array, function(it){ return it[0] === key; }); if(~index)this.array.splice(index, 1); return !!~index; } })[LEAK]; } module.exports = { getConstructor: function(NAME, IS_MAP, ADDER){ function C(){ $.set(assert.inst(this, C, NAME), ID, id++); var iterable = arguments[0]; if(iterable != undefined)forOf(iterable, IS_MAP, this[ADDER], this); } $.mix(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; if(isFrozen(key))return leakStore(this)['delete'](key); return _has(key, WEAK) && _has(key[WEAK], this[ID]) && delete key[WEAK][this[ID]]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; if(isFrozen(key))return leakStore(this).has(key); return _has(key, WEAK) && _has(key[WEAK], this[ID]); } }); return C; }, def: function(that, key, value){ if(isFrozen(assert.obj(key))){ leakStore(that).set(key, value); } else { _has(key, WEAK) || hide(key, WEAK, {}); key[WEAK][that[ID]] = value; } return that; }, leakStore: leakStore, WEAK: WEAK, ID: ID }; },{"./$":22,"./$.array-methods":4,"./$.assert":5,"./$.for-of":15,"./$.uid":31}],11:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def') , BUGGY = require('./$.iter').BUGGY , forOf = require('./$.for-of') , species = require('./$.species') , assertInstance = require('./$.assert').inst; module.exports = function(NAME, methods, common, IS_MAP, IS_WEAK){ var Base = $.g[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; function fixMethod(KEY, CHAIN){ var method = proto[KEY]; if($.FW)proto[KEY] = function(a, b){ var result = method.call(this, a === 0 ? 0 : a, b); return CHAIN ? this : result; }; } if(!$.isFunction(C) || !(IS_WEAK || !BUGGY && proto.forEach && proto.entries)){ // create collection constructor C = common.getConstructor(NAME, IS_MAP, ADDER); $.mix(C.prototype, methods); } else { var inst = new C , chain = inst[ADDER](IS_WEAK ? {} : -0, 1) , buggyZero; // wrap for init collections from iterable if(!require('./$.iter-detect')(function(iter){ new C(iter); })){ // eslint-disable-line no-new C = function(){ assertInstance(this, C, NAME); var that = new Base , iterable = arguments[0]; if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); return that; }; C.prototype = proto; if($.FW)proto.constructor = C; } IS_WEAK || inst.forEach(function(val, key){ buggyZero = 1 / key === -Infinity; }); // fix converting -0 key to +0 if(buggyZero){ fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } // + fix .add & .set for chaining if(buggyZero || chain !== inst)fixMethod(ADDER, true); } require('./$.cof').set(C, NAME); O[NAME] = C; $def($def.G + $def.W + $def.F * (C != Base), O); species(C); species($.core[NAME]); // for wrapper if(!IS_WEAK)common.setIter(C, NAME, IS_MAP); return C; }; },{"./$":22,"./$.assert":5,"./$.cof":7,"./$.def":13,"./$.for-of":15,"./$.iter":21,"./$.iter-detect":20,"./$.species":28}],12:[function(require,module,exports){ // Optional / simple context binding var assertFunction = require('./$.assert').fn; module.exports = function(fn, that, length){ assertFunction(fn); if(~length && that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; },{"./$.assert":5}],13:[function(require,module,exports){ var $ = require('./$') , global = $.g , core = $.core , isFunction = $.isFunction; function ctx(fn, that){ return function(){ return fn.apply(that, arguments); }; } global.core = core; // type bitmap $def.F = 1; // forced $def.G = 2; // global $def.S = 4; // static $def.P = 8; // proto $def.B = 16; // bind $def.W = 32; // wrap function $def(type, name, source){ var key, own, out, exp , isGlobal = type & $def.G , target = isGlobal ? global : type & $def.S ? global[name] : (global[name] || {}).prototype , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // contains in native own = !(type & $def.F) && target && key in target; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context if(type & $def.B && own)exp = ctx(out, global); else exp = type & $def.P && isFunction(out) ? ctx(Function.call, out) : out; // extend global if(target && !own){ if(isGlobal)target[key] = out; else delete target[key] && $.hide(target, key, out); } // export if(exports[key] != out)$.hide(exports, key, exp); } } module.exports = $def; },{"./$":22}],14:[function(require,module,exports){ var $ = require('./$'); module.exports = function(it){ var keys = $.getKeys(it) , getDesc = $.getDesc , getSymbols = $.getSymbols; if(getSymbols)$.each.call(getSymbols(it), function(key){ if(getDesc(it, key).enumerable)keys.push(key); }); return keys; }; },{"./$":22}],15:[function(require,module,exports){ var ctx = require('./$.ctx') , get = require('./$.iter').get , call = require('./$.iter-call'); module.exports = function(iterable, entries, fn, that){ var iterator = get(iterable) , f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done){ if(call(iterator, f, step.value, entries) === false){ return call.close(iterator); } } }; },{"./$.ctx":12,"./$.iter":21,"./$.iter-call":18}],16:[function(require,module,exports){ module.exports = function($){ $.FW = true; $.path = $.g; return $; }; },{}],17:[function(require,module,exports){ // Fast apply // http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); }; },{}],18:[function(require,module,exports){ var assertObject = require('./$.assert').obj; function close(iterator){ var ret = iterator['return']; if(ret !== undefined)assertObject(ret.call(iterator)); } function call(iterator, fn, value, entries){ try { return entries ? fn(assertObject(value)[0], value[1]) : fn(value); } catch(e){ close(iterator); throw e; } } call.close = close; module.exports = call; },{"./$.assert":5}],19:[function(require,module,exports){ var $def = require('./$.def') , $ = require('./$') , cof = require('./$.cof') , $iter = require('./$.iter') , SYMBOL_ITERATOR = require('./$.wks')('iterator') , FF_ITERATOR = '@@iterator' , VALUES = 'values' , Iterators = $iter.Iterators; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE){ $iter.create(Constructor, NAME, next); function createMethod(kind){ return function(){ return new Constructor(this, kind); }; } var TAG = NAME + ' Iterator' , proto = Base.prototype , _native = proto[SYMBOL_ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , _default = _native || createMethod(DEFAULT) , methods, key; // Fix native if(_native){ var IteratorPrototype = $.getProto(_default.call(new Base)); // Set @@toStringTag to native iterators cof.set(IteratorPrototype, TAG, true); // FF fix if($.FW && $.has(proto, FF_ITERATOR))$iter.set(IteratorPrototype, $.that); } // Define iterator if($.FW)$iter.set(proto, _default); // Plug for library Iterators[NAME] = _default; Iterators[TAG] = $.that; if(DEFAULT){ methods = { keys: IS_SET ? _default : createMethod('keys'), values: DEFAULT == VALUES ? _default : createMethod(VALUES), entries: DEFAULT != VALUES ? _default : createMethod('entries') }; if(FORCE)for(key in methods){ if(!(key in proto))$.hide(proto, key, methods[key]); } else $def($def.P + $def.F * $iter.BUGGY, NAME, methods); } }; },{"./$":22,"./$.cof":7,"./$.def":13,"./$.iter":21,"./$.wks":33}],20:[function(require,module,exports){ var SYMBOL_ITERATOR = require('./$.wks')('iterator') , SAFE_CLOSING = false; try { var riter = [7][SYMBOL_ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec){ if(!SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[SYMBOL_ITERATOR](); iter.next = function(){ safe = true; }; arr[SYMBOL_ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; },{"./$.wks":33}],21:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , assertObject = require('./$.assert').obj , SYMBOL_ITERATOR = require('./$.wks')('iterator') , FF_ITERATOR = '@@iterator' , Iterators = {} , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, $.that); function setIterator(O, value){ $.hide(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol if(FF_ITERATOR in [])$.hide(O, FF_ITERATOR, value); } module.exports = { // Safari has buggy iterators w/o `next` BUGGY: 'keys' in [] && !('next' in [].keys()), Iterators: Iterators, step: function(done, value){ return {value: value, done: !!done}; }, is: function(it){ var O = Object(it) , Symbol = $.g.Symbol , SYM = Symbol && Symbol.iterator || FF_ITERATOR; return SYM in O || SYMBOL_ITERATOR in O || $.has(Iterators, cof.classof(O)); }, get: function(it){ var Symbol = $.g.Symbol , ext = it[Symbol && Symbol.iterator || FF_ITERATOR] , getIter = ext || it[SYMBOL_ITERATOR] || Iterators[cof.classof(it)]; return assertObject(getIter.call(it)); }, set: setIterator, create: function(Constructor, NAME, next, proto){ Constructor.prototype = $.create(proto || IteratorPrototype, {next: $.desc(1, next)}); cof.set(Constructor, NAME + ' Iterator'); } }; },{"./$":22,"./$.assert":5,"./$.cof":7,"./$.wks":33}],22:[function(require,module,exports){ 'use strict'; var global = typeof self != 'undefined' ? self : Function('return this')() , core = {} , defineProperty = Object.defineProperty , hasOwnProperty = {}.hasOwnProperty , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min; // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. var DESC = !!function(){ try { return defineProperty({}, 'a', {get: function(){ return 2; }}).a == 2; } catch(e){ /* empty */ } }(); var hide = createDefiner(1); // 7.1.4 ToInteger function toInteger(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); } function desc(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return $.setDesc(object, key, desc(bitmap, value)); } : simpleSet; } function isObject(it){ return it !== null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } function assertDefined(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; } var $ = module.exports = require('./$.fw')({ g: global, core: core, html: global.document && document.documentElement, // http://jsperf.com/core-js-isobject isObject: isObject, isFunction: isFunction, it: function(it){ return it; }, that: function(){ return this; }, // 7.1.4 ToInteger toInteger: toInteger, // 7.1.15 ToLength toLength: function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }, toIndex: function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }, has: function(it, key){ return hasOwnProperty.call(it, key); }, create: Object.create, getProto: Object.getPrototypeOf, DESC: DESC, desc: desc, getDesc: Object.getOwnPropertyDescriptor, setDesc: defineProperty, setDescs: Object.defineProperties, getKeys: Object.keys, getNames: Object.getOwnPropertyNames, getSymbols: Object.getOwnPropertySymbols, assertDefined: assertDefined, // Dummy, fix for not array-like ES3 string in es5 module ES5Object: Object, toObject: function(it){ return $.ES5Object(assertDefined(it)); }, hide: hide, def: createDefiner(0), set: global.Symbol ? simpleSet : hide, mix: function(target, src){ for(var key in src)hide(target, key, src[key]); return target; }, each: [].forEach }); /* eslint-disable no-undef */ if(typeof __e != 'undefined')__e = core; if(typeof __g != 'undefined')__g = global; },{"./$.fw":16}],23:[function(require,module,exports){ var $ = require('./$'); module.exports = function(object, el){ var O = $.toObject(object) , keys = $.getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; },{"./$":22}],24:[function(require,module,exports){ var $ = require('./$') , assertObject = require('./$.assert').obj; module.exports = function ownKeys(it){ assertObject(it); var keys = $.getNames(it) , getSymbols = $.getSymbols; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; },{"./$":22,"./$.assert":5}],25:[function(require,module,exports){ 'use strict'; var $ = require('./$') , invoke = require('./$.invoke') , assertFunction = require('./$.assert').fn; module.exports = function(/* ...pargs */){ var fn = assertFunction(this) , length = arguments.length , pargs = Array(length) , i = 0 , _ = $.path._ , holder = false; while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; return function(/* ...args */){ var that = this , _length = arguments.length , j = 0, k = 0, args; if(!holder && !_length)return invoke(fn, pargs, that); args = pargs.slice(); if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++]; while(_length > k)args.push(arguments[k++]); return invoke(fn, args, that); }; }; },{"./$":22,"./$.assert":5,"./$.invoke":17}],26:[function(require,module,exports){ 'use strict'; module.exports = function(regExp, replace, isStatic){ var replacer = replace === Object(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(isStatic ? it : this).replace(regExp, replacer); }; }; },{}],27:[function(require,module,exports){ // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var $ = require('./$') , assert = require('./$.assert'); function check(O, proto){ assert.obj(O); assert(proto === null || $.isObject(proto), proto, ": can't set as prototype!"); } module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} // eslint-disable-line ? function(buggy, set){ try { set = require('./$.ctx')(Function.call, $.getDesc(Object.prototype, '__proto__').set, 2); set({}, []); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }() : undefined), check: check }; },{"./$":22,"./$.assert":5,"./$.ctx":12}],28:[function(require,module,exports){ var $ = require('./$') , SPECIES = require('./$.wks')('species'); module.exports = function(C){ if($.DESC && !(SPECIES in C))$.setDesc(C, SPECIES, { configurable: true, get: $.that }); }; },{"./$":22,"./$.wks":33}],29:[function(require,module,exports){ 'use strict'; // true -> String#at // false -> String#codePointAt var $ = require('./$'); module.exports = function(TO_STRING){ return function(pos){ var s = String($.assertDefined(this)) , i = $.toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; },{"./$":22}],30:[function(require,module,exports){ 'use strict'; var $ = require('./$') , ctx = require('./$.ctx') , cof = require('./$.cof') , invoke = require('./$.invoke') , global = $.g , isFunction = $.isFunction , html = $.html , document = global.document , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , postMessage = global.postMessage , addEventListener = global.addEventListener , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; function run(){ var id = +this; if($.has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run.call(event.data); } // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!isFunction(setTask) || !isFunction(clearTask)){ setTask = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function(id){ delete queue[id]; }; // Node.js 0.8- if(cof(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); }; addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } else if(document && ONREADYSTATECHANGE in document.createElement('script')){ defer = function(id){ html.appendChild(document.createElement('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; },{"./$":22,"./$.cof":7,"./$.ctx":12,"./$.invoke":17}],31:[function(require,module,exports){ var sid = 0; function uid(key){ return 'Symbol(' + key + ')_' + (++sid + Math.random()).toString(36); } uid.safe = require('./$').g.Symbol || uid; module.exports = uid; },{"./$":22}],32:[function(require,module,exports){ // 22.1.3.31 Array.prototype[@@unscopables] var $ = require('./$') , UNSCOPABLES = require('./$.wks')('unscopables'); if($.FW && !(UNSCOPABLES in []))$.hide(Array.prototype, UNSCOPABLES, {}); module.exports = function(key){ if($.FW)[][UNSCOPABLES][key] = true; }; },{"./$":22,"./$.wks":33}],33:[function(require,module,exports){ var global = require('./$').g , store = {}; module.exports = function(name){ return store[name] || (store[name] = global.Symbol && global.Symbol[name] || require('./$.uid').safe('Symbol.' + name)); }; },{"./$":22,"./$.uid":31}],34:[function(require,module,exports){ var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def') , invoke = require('./$.invoke') , arrayMethod = require('./$.array-methods') , IE_PROTO = require('./$.uid').safe('__proto__') , assert = require('./$.assert') , assertObject = assert.obj , ObjectProto = Object.prototype , A = [] , slice = A.slice , indexOf = A.indexOf , classof = cof.classof , has = $.has , defineProperty = $.setDesc , getOwnDescriptor = $.getDesc , defineProperties = $.setDescs , isFunction = $.isFunction , toObject = $.toObject , toLength = $.toLength , IE8_DOM_DEFINE = false; if(!$.DESC){ try { IE8_DOM_DEFINE = defineProperty(document.createElement('div'), 'x', {get: function(){ return 8; }} ).x == 8; } catch(e){ /* empty */ } $.setDesc = function(O, P, Attributes){ if(IE8_DOM_DEFINE)try { return defineProperty(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)assertObject(O)[P] = Attributes.value; return O; }; $.getDesc = function(O, P){ if(IE8_DOM_DEFINE)try { return getOwnDescriptor(O, P); } catch(e){ /* empty */ } if(has(O, P))return $.desc(!ObjectProto.propertyIsEnumerable.call(O, P), O[P]); }; $.setDescs = defineProperties = function(O, Properties){ assertObject(O); var keys = $.getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)$.setDesc(O, P = keys[i++], Properties[P]); return O; }; } $def($def.S + $def.F * !$.DESC, 'Object', { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $.getDesc, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: $.setDesc, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = ('constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,' + 'toLocaleString,toString,valueOf').split(',') // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', 'prototype') , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = document.createElement('iframe') , i = keysLen1 , gt = '>' , iframeDocument; iframe.style.display = 'none'; $.html.appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict.prototype[keys1[i]]; return createDict(); }; function createGetKeys(names, length){ return function(object){ var O = toObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~indexOf.call(result, key) || result.push(key); } return result; }; } function isPrimitive(it){ return !$.isObject(it); } function Empty(){} $def($def.S, 'Object', { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: $.getProto = $.getProto || function(O){ O = Object(assert.def(O)); if(has(O, IE_PROTO))return O[IE_PROTO]; if(isFunction(O.constructor) && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: $.getNames = $.getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: $.create = $.create || function(O, /*?*/Properties){ var result; if(O !== null){ Empty.prototype = assertObject(O); result = new Empty(); Empty.prototype = null; // add "__proto__" for Object.getPrototypeOf shim result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: $.getKeys = $.getKeys || createGetKeys(keys1, keysLen1, false), // 19.1.2.17 / 15.2.3.8 Object.seal(O) seal: $.it, // <- cap // 19.1.2.5 / 15.2.3.9 Object.freeze(O) freeze: $.it, // <- cap // 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O) preventExtensions: $.it, // <- cap // 19.1.2.13 / 15.2.3.11 Object.isSealed(O) isSealed: isPrimitive, // <- cap // 19.1.2.12 / 15.2.3.12 Object.isFrozen(O) isFrozen: isPrimitive, // <- cap // 19.1.2.11 / 15.2.3.13 Object.isExtensible(O) isExtensible: $.isObject // <- cap }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $def($def.P, 'Function', { bind: function(that /*, args... */){ var fn = assert.fn(this) , partArgs = slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(slice.call(arguments)); return invoke(fn, args, this instanceof bound ? $.create(fn.prototype) : that); } if(fn.prototype)bound.prototype = fn.prototype; return bound; } }); // Fix for not array-like ES3 string function arrayMethodFix(fn){ return function(){ return fn.apply($.ES5Object(this), arguments); }; } if(!(0 in Object('z') && 'z'[0] == 'z')){ $.ES5Object = function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; } $def($def.P + $def.F * ($.ES5Object != Object), 'Array', { slice: arrayMethodFix(slice), join: arrayMethodFix(A.join) }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $def($def.S, 'Array', { isArray: function(arg){ return cof(arg) == 'Array'; } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assert.fn(callbackfn); var O = toObject(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(arguments.length < 2)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; assert(isRight ? index >= 0 : length > index, 'Reduce of empty array with no initial value'); } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; }; } $def($def.P, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: $.each = $.each || arrayMethod(0), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: arrayMethod(1), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: arrayMethod(2), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: arrayMethod(3), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: arrayMethod(4), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: indexOf = indexOf || require('./$.array-includes')(false), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = toObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = Math.min(index, $.toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $def($def.P, 'String', {trim: require('./$.replacer')(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $def($def.S, 'Date', {now: function(){ return +new Date; }}); function lz(num){ return num > 9 ? num : '0' + num; } // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() // PhantomJS and old webkit had a broken Date implementation. var date = new Date(-5e13 - 1) , brokenDate = !(date.toISOString && date.toISOString() == '0385-07-25T07:06:39.999Z'); $def($def.P + $def.F * brokenDate, 'Date', {toISOString: function(){ if(!isFinite(this))throw RangeError('Invalid time value'); var d = this , y = d.getUTCFullYear() , m = d.getUTCMilliseconds() , s = y < 0 ? '-' : y > 9999 ? '+' : ''; return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; }}); if(classof(function(){ return arguments; }()) == 'Object')cof.classof = function(it){ var tag = classof(it); return tag == 'Object' && isFunction(it.callee) ? 'Arguments' : tag; }; },{"./$":22,"./$.array-includes":3,"./$.array-methods":4,"./$.assert":5,"./$.cof":7,"./$.def":13,"./$.invoke":17,"./$.replacer":26,"./$.uid":31}],35:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def') , toIndex = $.toIndex; $def($def.P, 'Array', { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) copyWithin: function copyWithin(target/* = 0 */, start /* = 0, end = @length */){ var O = Object($.assertDefined(this)) , len = $.toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments[2] , fin = end === undefined ? len : toIndex(end, len) , count = Math.min(fin - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from = from + count - 1; to = to + count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; } }); require('./$.unscope')('copyWithin'); },{"./$":22,"./$.def":13,"./$.unscope":32}],36:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def') , toIndex = $.toIndex; $def($def.P, 'Array', { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function fill(value /*, start = 0, end = @length */){ var O = Object($.assertDefined(this)) , length = $.toLength(O.length) , index = toIndex(arguments[1], length) , end = arguments[2] , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; } }); require('./$.unscope')('fill'); },{"./$":22,"./$.def":13,"./$.unscope":32}],37:[function(require,module,exports){ var $def = require('./$.def'); $def($def.P, 'Array', { // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) findIndex: require('./$.array-methods')(6) }); require('./$.unscope')('findIndex'); },{"./$.array-methods":4,"./$.def":13,"./$.unscope":32}],38:[function(require,module,exports){ var $def = require('./$.def'); $def($def.P, 'Array', { // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) find: require('./$.array-methods')(5) }); require('./$.unscope')('find'); },{"./$.array-methods":4,"./$.def":13,"./$.unscope":32}],39:[function(require,module,exports){ var $ = require('./$') , ctx = require('./$.ctx') , $def = require('./$.def') , $iter = require('./$.iter') , call = require('./$.iter-call'); $def($def.S + $def.F * !require('./$.iter-detect')(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = Object($.assertDefined(arrayLike)) , mapfn = arguments[1] , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, arguments[2], 2) : undefined , index = 0 , length, result, step, iterator; if($iter.is(O)){ iterator = $iter.get(O); // strange IE quirks mode bug -> use typeof instead of isFunction result = new (typeof this == 'function' ? this : Array); for(; !(step = iterator.next()).done; index++){ result[index] = mapping ? call(iterator, f, [step.value, index], true) : step.value; } } else { // strange IE quirks mode bug -> use typeof instead of isFunction result = new (typeof this == 'function' ? this : Array)(length = $.toLength(O.length)); for(; length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } } result.length = index; return result; } }); },{"./$":22,"./$.ctx":12,"./$.def":13,"./$.iter":21,"./$.iter-call":18,"./$.iter-detect":20}],40:[function(require,module,exports){ var $ = require('./$') , setUnscope = require('./$.unscope') , ITER = require('./$.uid').safe('iter') , $iter = require('./$.iter') , step = $iter.step , Iterators = $iter.Iterators; // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() require('./$.iter-define')(Array, 'Array', function(iterated, kind){ $.set(this, ITER, {o: $.toObject(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , index = iter.i++; if(!O || index >= O.length){ iter.o = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; setUnscope('keys'); setUnscope('values'); setUnscope('entries'); },{"./$":22,"./$.iter":21,"./$.iter-define":19,"./$.uid":31,"./$.unscope":32}],41:[function(require,module,exports){ var $def = require('./$.def'); $def($def.S, 'Array', { // 22.1.2.3 Array.of( ...items) of: function of(/* ...args */){ var index = 0 , length = arguments.length // strange IE quirks mode bug -> use typeof instead of isFunction , result = new (typeof this == 'function' ? this : Array)(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); },{"./$.def":13}],42:[function(require,module,exports){ require('./$.species')(Array); },{"./$.species":28}],43:[function(require,module,exports){ 'use strict'; var $ = require('./$') , NAME = 'name' , setDesc = $.setDesc , FunctionProto = Function.prototype; // 19.2.4.2 name NAME in FunctionProto || $.FW && $.DESC && setDesc(FunctionProto, NAME, { configurable: true, get: function(){ var match = String(this).match(/^\s*function ([^ (]*)/) , name = match ? match[1] : ''; $.has(this, NAME) || setDesc(this, NAME, $.desc(5, name)); return name; }, set: function(value){ $.has(this, NAME) || setDesc(this, NAME, $.desc(0, value)); } }); },{"./$":22}],44:[function(require,module,exports){ 'use strict'; var strong = require('./$.collection-strong'); // 23.1 Map Objects require('./$.collection')('Map', { // 23.1.3.6 Map.prototype.get(key) get: function get(key){ var entry = strong.getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value){ return strong.def(this, key === 0 ? 0 : key, value); } }, strong, true); },{"./$.collection":11,"./$.collection-strong":8}],45:[function(require,module,exports){ var Infinity = 1 / 0 , $def = require('./$.def') , E = Math.E , pow = Math.pow , abs = Math.abs , exp = Math.exp , log = Math.log , sqrt = Math.sqrt , ceil = Math.ceil , floor = Math.floor , EPSILON = pow(2, -52) , EPSILON32 = pow(2, -23) , MAX32 = pow(2, 127) * (2 - EPSILON32) , MIN32 = pow(2, -126); function roundTiesToEven(n){ return n + 1 / EPSILON - 1 / EPSILON; } // 20.2.2.28 Math.sign(x) function sign(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; } // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } // 20.2.2.14 Math.expm1(x) function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1; } $def($def.S, 'Math', { // 20.2.2.3 Math.acosh(x) acosh: function acosh(x){ return (x = +x) < 1 ? NaN : isFinite(x) ? log(x / E + sqrt(x + 1) * sqrt(x - 1) / E) + 1 : x; }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function atanh(x){ return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function cbrt(x){ return sign(x = +x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32(x) clz32: function clz32(x){ return (x >>>= 0) ? 31 - floor(log(x + 0.5) * Math.LOG2E) : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function cosh(x){ return (exp(x = +x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: expm1, // 20.2.2.16 Math.fround(x) fround: function fround(x){ var $abs = abs(x) , $sign = sign(x) , a, result; if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; a = (1 + EPSILON32 / EPSILON) * $abs; result = a - (a - $abs); if(result > MAX32 || result != result)return $sign * Infinity; return $sign * result; }, // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , len1 = arguments.length , len2 = len1 , args = Array(len1) , larg = -Infinity , arg; while(len1--){ arg = args[len1] = +arguments[len1]; if(arg == Infinity || arg == -Infinity)return Infinity; if(arg > larg)larg = arg; } larg = arg || 1; while(len2--)sum += pow(args[len2] / larg, 2); return larg * sqrt(sum); }, // 20.2.2.18 Math.imul(x, y) imul: function imul(x, y){ var UInt16 = 0xffff , xn = +x , yn = +y , xl = UInt16 & xn , yl = UInt16 & yn; return 0 | xl * yl + ((UInt16 & xn >>> 16) * yl + xl * (UInt16 & yn >>> 16) << 16 >>> 0); }, // 20.2.2.20 Math.log1p(x) log1p: function log1p(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x); }, // 20.2.2.21 Math.log10(x) log10: function log10(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function log2(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function sinh(x){ return abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2); }, // 20.2.2.33 Math.tanh(x) tanh: function tanh(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); }, // 20.2.2.34 Math.trunc(x) trunc: function trunc(it){ return (it > 0 ? floor : ceil)(it); } }); },{"./$.def":13}],46:[function(require,module,exports){ 'use strict'; var $ = require('./$') , isObject = $.isObject , isFunction = $.isFunction , NUMBER = 'Number' , Number = $.g[NUMBER] , Base = Number , proto = Number.prototype; function toPrimitive(it){ var fn, val; if(isFunction(fn = it.valueOf) && !isObject(val = fn.call(it)))return val; if(isFunction(fn = it.toString) && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to number"); } function toNumber(it){ if(isObject(it))it = toPrimitive(it); if(typeof it == 'string' && it.length > 2 && it.charCodeAt(0) == 48){ var binary = false; switch(it.charCodeAt(1)){ case 66 : case 98 : binary = true; case 79 : case 111 : return parseInt(it.slice(2), binary ? 2 : 8); } } return +it; } if($.FW && !(Number('0o1') && Number('0b1'))){ Number = function Number(it){ return this instanceof Number ? new Base(toNumber(it)) : toNumber(it); }; $.each.call($.DESC ? $.getNames(Base) : ( // ES3: 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES6 (in case, if modules with ES6 Number statics required before): 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' ).split(','), function(key){ if($.has(Base, key) && !$.has(Number, key)){ $.setDesc(Number, key, $.getDesc(Base, key)); } } ); Number.prototype = proto; proto.constructor = Number; $.hide($.g, NUMBER, Number); } },{"./$":22}],47:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def') , abs = Math.abs , floor = Math.floor , _isFinite = $.g.isFinite , MAX_SAFE_INTEGER = 0x1fffffffffffff; // pow(2, 53) - 1 == 9007199254740991; function isInteger(it){ return !$.isObject(it) && _isFinite(it) && floor(it) === it; } $def($def.S, 'Number', { // 20.1.2.1 Number.EPSILON EPSILON: Math.pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function isFinite(it){ return typeof it == 'number' && _isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: function isNaN(number){ return number != number; }, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function isSafeInteger(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); },{"./$":22,"./$.def":13}],48:[function(require,module,exports){ // 19.1.3.1 Object.assign(target, source) var $def = require('./$.def'); $def($def.S, 'Object', {assign: require('./$.assign')}); },{"./$.assign":6,"./$.def":13}],49:[function(require,module,exports){ // 19.1.3.10 Object.is(value1, value2) var $def = require('./$.def'); $def($def.S, 'Object', { is: function is(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } }); },{"./$.def":13}],50:[function(require,module,exports){ // 19.1.3.19 Object.setPrototypeOf(O, proto) var $def = require('./$.def'); $def($def.S, 'Object', {setPrototypeOf: require('./$.set-proto').set}); },{"./$.def":13,"./$.set-proto":27}],51:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def') , isObject = $.isObject , toObject = $.toObject; function wrapObjectMethod(METHOD, MODE){ var fn = ($.core.Object || {})[METHOD] || Object[METHOD] , f = 0 , o = {}; o[METHOD] = MODE == 1 ? function(it){ return isObject(it) ? fn(it) : it; } : MODE == 2 ? function(it){ return isObject(it) ? fn(it) : true; } : MODE == 3 ? function(it){ return isObject(it) ? fn(it) : false; } : MODE == 4 ? function getOwnPropertyDescriptor(it, key){ return fn(toObject(it), key); } : MODE == 5 ? function getPrototypeOf(it){ return fn(Object($.assertDefined(it))); } : function(it){ return fn(toObject(it)); }; try { fn('z'); } catch(e){ f = 1; } $def($def.S + $def.F * f, 'Object', o); } wrapObjectMethod('freeze', 1); wrapObjectMethod('seal', 1); wrapObjectMethod('preventExtensions', 1); wrapObjectMethod('isFrozen', 2); wrapObjectMethod('isSealed', 2); wrapObjectMethod('isExtensible', 3); wrapObjectMethod('getOwnPropertyDescriptor', 4); wrapObjectMethod('getPrototypeOf', 5); wrapObjectMethod('keys'); wrapObjectMethod('getOwnPropertyNames'); },{"./$":22,"./$.def":13}],52:[function(require,module,exports){ 'use strict'; // 19.1.3.6 Object.prototype.toString() var $ = require('./$') , cof = require('./$.cof') , tmp = {}; tmp[require('./$.wks')('toStringTag')] = 'z'; if($.FW && cof(tmp) != 'z')$.hide(Object.prototype, 'toString', function toString(){ return '[object ' + cof.classof(this) + ']'; }); },{"./$":22,"./$.cof":7,"./$.wks":33}],53:[function(require,module,exports){ 'use strict'; var $ = require('./$') , ctx = require('./$.ctx') , cof = require('./$.cof') , $def = require('./$.def') , assert = require('./$.assert') , forOf = require('./$.for-of') , setProto = require('./$.set-proto').set , species = require('./$.species') , SPECIES = require('./$.wks')('species') , RECORD = require('./$.uid').safe('record') , PROMISE = 'Promise' , global = $.g , process = global.process , asap = process && process.nextTick || require('./$.task').set , P = global[PROMISE] , isFunction = $.isFunction , isObject = $.isObject , assertFunction = assert.fn , assertObject = assert.obj , test; var useNative = isFunction(P) && isFunction(P.resolve) && P.resolve(test = new P(function(){})) == test; // actual Firefox has broken subclass support, test that function P2(x){ var self = new P(x); setProto(self, P2.prototype); return self; } if(useNative){ try { // protect against bad/buggy Object.setPrototype setProto(P2, P); P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); if(!(P2.resolve(5).then(function(){}) instanceof P2)){ useNative = false; } } catch(e){ useNative = false; } } // helpers function getConstructor(C){ var S = assertObject(C)[SPECIES]; return S != undefined ? S : C; } function isThenable(it){ var then; if(isObject(it))then = it.then; return isFunction(then) ? then : false; } function notify(record){ var chain = record.c; if(chain.length)asap(function(){ var value = record.v , ok = record.s == 1 , i = 0; while(chain.length > i)!function(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ if(!ok)record.h = true; ret = cb === true ? value : cb(value); if(ret === react.P){ react.rej(TypeError('Promise-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(value); } catch(err){ react.rej(err); } }(chain[i++]); chain.length = 0; }); } function isUnhandled(promise){ var record = promise[RECORD] , chain = record.a , i = 0 , react; if(record.h)return false; while(chain.length > i){ react = chain[i++]; if(react.fail || !isUnhandled(react.P))return false; } return true; } function $reject(value){ var record = this , promise; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; asap(function(){ setTimeout(function(){ if(isUnhandled(promise = record.p)){ if(cof(process) == 'process'){ process.emit('unhandledRejection', value, promise); } else if(global.console && isFunction(console.error)){ console.error('Unhandled promise rejection', value); } } }, 1); }); notify(record); } function $resolve(value){ var record = this , then, wrapper; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(then = isThenable(value)){ wrapper = {r: record, d: false}; // wrap then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } else { record.v = value; record.s = 1; notify(record); } } catch(err){ $reject.call(wrapper || {r: record, d: false}, err); // wrap } } // constructor polyfill if(!useNative){ // 25.4.3.1 Promise(executor) P = function Promise(executor){ assertFunction(executor); var record = { p: assert.inst(this, P, PROMISE), // <- promise c: [], // <- awaiting reactions a: [], // <- all reactions s: 0, // <- state d: false, // <- done v: undefined, // <- value h: false // <- handled rejection }; $.hide(this, RECORD, record); try { executor(ctx($resolve, record, 1), ctx($reject, record, 1)); } catch(err){ $reject.call(record, err); } }; $.mix(P.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var S = assertObject(assertObject(this).constructor)[SPECIES]; var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false }; var promise = react.P = new (S != undefined ? S : P)(function(res, rej){ react.res = assertFunction(res); react.rej = assertFunction(rej); }); var record = this[RECORD]; record.a.push(react); record.c.push(react); record.s && notify(record); return promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); } // export $def($def.G + $def.W + $def.F * !useNative, {Promise: P}); cof.set(P, PROMISE); species(P); species($.core[PROMISE]); // for wrapper // statics $def($def.S + $def.F * !useNative, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ return new (getConstructor(this))(function(res, rej){ rej(r); }); }, // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ return isObject(x) && RECORD in x && $.getProto(x) === this.prototype ? x : new (getConstructor(this))(function(res){ res(x); }); } }); $def($def.S + $def.F * !(useNative && require('./$.iter-detect')(function(iter){ P.all(iter)['catch'](function(){}); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = getConstructor(this) , values = []; return new C(function(res, rej){ forOf(iterable, false, values.push, values); var remaining = values.length , results = Array(remaining); if(remaining)$.each.call(values, function(promise, index){ C.resolve(promise).then(function(value){ results[index] = value; --remaining || res(results); }, rej); }); else res(results); }); }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = getConstructor(this); return new C(function(res, rej){ forOf(iterable, false, function(promise){ C.resolve(promise).then(res, rej); }); }); } }); },{"./$":22,"./$.assert":5,"./$.cof":7,"./$.ctx":12,"./$.def":13,"./$.for-of":15,"./$.iter-detect":20,"./$.set-proto":27,"./$.species":28,"./$.task":30,"./$.uid":31,"./$.wks":33}],54:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def') , setProto = require('./$.set-proto') , $iter = require('./$.iter') , ITER = require('./$.uid').safe('iter') , step = $iter.step , assert = require('./$.assert') , isObject = $.isObject , getDesc = $.getDesc , setDesc = $.setDesc , getProto = $.getProto , apply = Function.apply , assertObject = assert.obj , _isExtensible = Object.isExtensible || $.it; function Enumerate(iterated){ $.set(this, ITER, {o: iterated, k: undefined, i: 0}); } $iter.create(Enumerate, 'Object', function(){ var iter = this[ITER] , keys = iter.k , key; if(keys == undefined){ iter.k = keys = []; for(key in iter.o)keys.push(key); } do { if(iter.i >= keys.length)return step(1); } while(!((key = keys[iter.i++]) in iter.o)); return step(0, key); }); function wrap(fn){ return function(it){ assertObject(it); try { fn.apply(undefined, arguments); return true; } catch(e){ return false; } }; } function get(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc = getDesc(assertObject(target), propertyKey), proto; if(desc)return $.has(desc, 'value') ? desc.value : desc.get === undefined ? undefined : desc.get.call(receiver); return isObject(proto = getProto(target)) ? get(proto, propertyKey, receiver) : undefined; } function set(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = getDesc(assertObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = getProto(target))){ return set(proto, propertyKey, V, receiver); } ownDesc = $.desc(0); } if($.has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = getDesc(receiver, propertyKey) || $.desc(0); existingDescriptor.value = V; setDesc(receiver, propertyKey, existingDescriptor); return true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } var reflect = { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) apply: require('./$.ctx')(Function.call, apply, 3), // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) construct: function construct(target, argumentsList /*, newTarget*/){ var proto = assert.fn(arguments.length < 3 ? target : arguments[2]).prototype , instance = $.create(isObject(proto) ? proto : Object.prototype) , result = apply.call(target, instance, argumentsList); return isObject(result) ? result : instance; }, // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) defineProperty: wrap(setDesc), // 26.1.4 Reflect.deleteProperty(target, propertyKey) deleteProperty: function deleteProperty(target, propertyKey){ var desc = getDesc(assertObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; }, // 26.1.5 Reflect.enumerate(target) enumerate: function enumerate(target){ return new Enumerate(assertObject(target)); }, // 26.1.6 Reflect.get(target, propertyKey [, receiver]) get: get, // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ return getDesc(assertObject(target), propertyKey); }, // 26.1.8 Reflect.getPrototypeOf(target) getPrototypeOf: function getPrototypeOf(target){ return getProto(assertObject(target)); }, // 26.1.9 Reflect.has(target, propertyKey) has: function has(target, propertyKey){ return propertyKey in target; }, // 26.1.10 Reflect.isExtensible(target) isExtensible: function isExtensible(target){ return !!_isExtensible(assertObject(target)); }, // 26.1.11 Reflect.ownKeys(target) ownKeys: require('./$.own-keys'), // 26.1.12 Reflect.preventExtensions(target) preventExtensions: wrap(Object.preventExtensions || $.it), // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) set: set }; // 26.1.14 Reflect.setPrototypeOf(target, proto) if(setProto)reflect.setPrototypeOf = function setPrototypeOf(target, proto){ setProto.check(target, proto); try { setProto.set(target, proto); return true; } catch(e){ return false; } }; $def($def.G, {Reflect: {}}); $def($def.S, 'Reflect', reflect); },{"./$":22,"./$.assert":5,"./$.ctx":12,"./$.def":13,"./$.iter":21,"./$.own-keys":24,"./$.set-proto":27,"./$.uid":31}],55:[function(require,module,exports){ var $ = require('./$') , cof = require('./$.cof') , RegExp = $.g.RegExp , Base = RegExp , proto = RegExp.prototype; function regExpBroken() { try { var a = /a/g; // "new" creates a new object if (a === new RegExp(a)) { return true; } // RegExp allows a regex with flags as the pattern return RegExp(/a/g, 'i') != '/a/i'; } catch(e) { return true; } } if($.FW && $.DESC){ if(regExpBroken()) { RegExp = function RegExp(pattern, flags){ return new Base(cof(pattern) == 'RegExp' ? pattern.source : pattern, flags === undefined ? pattern.flags : flags); }; $.each.call($.getNames(Base), function(key){ key in RegExp || $.setDesc(RegExp, key, { configurable: true, get: function(){ return Base[key]; }, set: function(it){ Base[key] = it; } }); }); proto.constructor = RegExp; RegExp.prototype = proto; $.hide($.g, 'RegExp', RegExp); } // 21.2.5.3 get RegExp.prototype.flags() if(/./g.flags != 'g')$.setDesc(proto, 'flags', { configurable: true, get: require('./$.replacer')(/^.*\/(\w*)$/, '$1') }); } require('./$.species')(RegExp); },{"./$":22,"./$.cof":7,"./$.replacer":26,"./$.species":28}],56:[function(require,module,exports){ 'use strict'; var strong = require('./$.collection-strong'); // 23.2 Set Objects require('./$.collection')('Set', { // 23.2.3.1 Set.prototype.add(value) add: function add(value){ return strong.def(this, value = value === 0 ? 0 : value, value); } }, strong); },{"./$.collection":11,"./$.collection-strong":8}],57:[function(require,module,exports){ var $def = require('./$.def'); $def($def.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: require('./$.string-at')(false) }); },{"./$.def":13,"./$.string-at":29}],58:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def') , toLength = $.toLength; $def($def.P, 'String', { // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) endsWith: function endsWith(searchString /*, endPosition = @length */){ if(cof(searchString) == 'RegExp')throw TypeError(); var that = String($.assertDefined(this)) , endPosition = arguments[1] , len = toLength(that.length) , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); searchString += ''; return that.slice(end - searchString.length, end) === searchString; } }); },{"./$":22,"./$.cof":7,"./$.def":13}],59:[function(require,module,exports){ var $def = require('./$.def') , toIndex = require('./$').toIndex , fromCharCode = String.fromCharCode; $def($def.S, 'String', { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars var res = [] , len = arguments.length , i = 0 , code; while(len > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); } }); },{"./$":22,"./$.def":13}],60:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def'); $def($def.P, 'String', { // 21.1.3.7 String.prototype.includes(searchString, position = 0) includes: function includes(searchString /*, position = 0 */){ if(cof(searchString) == 'RegExp')throw TypeError(); return !!~String($.assertDefined(this)).indexOf(searchString, arguments[1]); } }); },{"./$":22,"./$.cof":7,"./$.def":13}],61:[function(require,module,exports){ var set = require('./$').set , at = require('./$.string-at')(true) , ITER = require('./$.uid').safe('iter') , $iter = require('./$.iter') , step = $iter.step; // 21.1.3.27 String.prototype[@@iterator]() require('./$.iter-define')(String, 'String', function(iterated){ set(this, ITER, {o: String(iterated), i: 0}); // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , index = iter.i , point; if(index >= O.length)return step(1); point = at.call(O, index); iter.i += point.length; return step(0, point); }); },{"./$":22,"./$.iter":21,"./$.iter-define":19,"./$.string-at":29,"./$.uid":31}],62:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def'); $def($def.S, 'String', { // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function raw(callSite){ var tpl = $.toObject(callSite.raw) , len = $.toLength(tpl.length) , sln = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(tpl[i++])); if(i < sln)res.push(String(arguments[i])); } return res.join(''); } }); },{"./$":22,"./$.def":13}],63:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def'); $def($def.P, 'String', { // 21.1.3.13 String.prototype.repeat(count) repeat: function repeat(count){ var str = String($.assertDefined(this)) , res = '' , n = $.toInteger(count); if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; } }); },{"./$":22,"./$.def":13}],64:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def'); $def($def.P, 'String', { // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function startsWith(searchString /*, position = 0 */){ if(cof(searchString) == 'RegExp')throw TypeError(); var that = String($.assertDefined(this)) , index = $.toLength(Math.min(arguments[1], that.length)); searchString += ''; return that.slice(index, index + searchString.length) === searchString; } }); },{"./$":22,"./$.cof":7,"./$.def":13}],65:[function(require,module,exports){ 'use strict'; // ECMAScript 6 symbols shim var $ = require('./$') , setTag = require('./$.cof').set , uid = require('./$.uid') , $def = require('./$.def') , keyOf = require('./$.keyof') , enumKeys = require('./$.enum-keys') , assertObject = require('./$.assert').obj , has = $.has , $create = $.create , getDesc = $.getDesc , setDesc = $.setDesc , desc = $.desc , getNames = $.getNames , toObject = $.toObject , Symbol = $.g.Symbol , setter = false , TAG = uid('tag') , HIDDEN = uid('hidden') , SymbolRegistry = {} , AllSymbols = {} , useNative = $.isFunction(Symbol); function wrap(tag){ var sym = AllSymbols[tag] = $.set($create(Symbol.prototype), TAG, tag); $.DESC && setter && setDesc(Object.prototype, tag, { configurable: true, set: function(value){ if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setDesc(this, tag, desc(1, value)); } }); return sym; } function defineProperty(it, key, D){ if(D && has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))setDesc(it, HIDDEN, desc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D.enumerable = false; } } return setDesc(it, key, D); } function defineProperties(it, P){ assertObject(it); var keys = enumKeys(P = toObject(P)) , i = 0 , l = keys.length , key; while(l > i)defineProperty(it, key = keys[i++], P[key]); return it; } function create(it, P){ return P === undefined ? $create(it) : defineProperties($create(it), P); } function getOwnPropertyDescriptor(it, key){ var D = getDesc(it = toObject(it), key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; } function getOwnPropertyNames(it){ var names = getNames(toObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN)result.push(key); return result; } function getOwnPropertySymbols(it){ var names = getNames(toObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]); return result; } // 19.4.1.1 Symbol([description]) if(!useNative){ Symbol = function Symbol(description){ if(this instanceof Symbol)throw TypeError('Symbol is not a constructor'); return wrap(uid(description)); }; $.hide(Symbol.prototype, 'toString', function(){ return this[TAG]; }); $.create = create; $.setDesc = defineProperty; $.getDesc = getOwnPropertyDescriptor; $.setDescs = defineProperties; $.getNames = getOwnPropertyNames; $.getSymbols = getOwnPropertySymbols; } var symbolStatics = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ return keyOf(SymbolRegistry, key); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.4 Symbol.iterator // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.10 Symbol.species // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive // 19.4.2.13 Symbol.toStringTag // 19.4.2.14 Symbol.unscopables $.each.call(( 'hasInstance,isConcatSpreadable,iterator,match,replace,search,' + 'species,split,toPrimitive,toStringTag,unscopables' ).split(','), function(it){ var sym = require('./$.wks')(it); symbolStatics[it] = useNative ? sym : wrap(sym); } ); setter = true; $def($def.G + $def.W, {Symbol: Symbol}); $def($def.S, 'Symbol', symbolStatics); $def($def.S + $def.F * !useNative, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: getOwnPropertySymbols }); // 19.4.3.5 Symbol.prototype[@@toStringTag] setTag(Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setTag($.g.JSON, 'JSON', true); },{"./$":22,"./$.assert":5,"./$.cof":7,"./$.def":13,"./$.enum-keys":14,"./$.keyof":23,"./$.uid":31,"./$.wks":33}],66:[function(require,module,exports){ 'use strict'; var $ = require('./$') , weak = require('./$.collection-weak') , leakStore = weak.leakStore , ID = weak.ID , WEAK = weak.WEAK , has = $.has , isObject = $.isObject , isFrozen = Object.isFrozen || $.core.Object.isFrozen , tmp = {}; // 23.3 WeakMap Objects var WeakMap = require('./$.collection')('WeakMap', { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ if(isFrozen(key))return leakStore(this).get(key); if(has(key, WEAK))return key[WEAK][this[ID]]; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return weak.def(this, key, value); } }, weak, true, true); // IE11 WeakMap frozen keys fix if($.FW && new WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ $.each.call(['delete', 'has', 'get', 'set'], function(key){ var method = WeakMap.prototype[key]; WeakMap.prototype[key] = function(a, b){ // store frozen objects on leaky map if(isObject(a) && isFrozen(a)){ var result = leakStore(this)[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }; }); } },{"./$":22,"./$.collection":11,"./$.collection-weak":10}],67:[function(require,module,exports){ 'use strict'; var weak = require('./$.collection-weak'); // 23.4 WeakSet Objects require('./$.collection')('WeakSet', { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value){ return weak.def(this, value, true); } }, weak, false, true); },{"./$.collection":11,"./$.collection-weak":10}],68:[function(require,module,exports){ // https://github.com/domenic/Array.prototype.includes var $def = require('./$.def'); $def($def.P, 'Array', { includes: require('./$.array-includes')(true) }); require('./$.unscope')('includes'); },{"./$.array-includes":3,"./$.def":13,"./$.unscope":32}],69:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON require('./$.collection-to-json')('Map'); },{"./$.collection-to-json":9}],70:[function(require,module,exports){ // https://gist.github.com/WebReflection/9353781 var $ = require('./$') , $def = require('./$.def') , ownKeys = require('./$.own-keys'); $def($def.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ var O = $.toObject(object) , result = {}; $.each.call(ownKeys(O), function(key){ $.setDesc(result, key, $.desc(0, $.getDesc(O, key))); }); return result; } }); },{"./$":22,"./$.def":13,"./$.own-keys":24}],71:[function(require,module,exports){ // http://goo.gl/XkBrjD var $ = require('./$') , $def = require('./$.def'); function createObjectToArray(isEntries){ return function(object){ var O = $.toObject(object) , keys = $.getKeys(O) , length = keys.length , i = 0 , result = Array(length) , key; if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]]; else while(length > i)result[i] = O[keys[i++]]; return result; }; } $def($def.S, 'Object', { values: createObjectToArray(false), entries: createObjectToArray(true) }); },{"./$":22,"./$.def":13}],72:[function(require,module,exports){ // https://gist.github.com/kangax/9698100 var $def = require('./$.def'); $def($def.S, 'RegExp', { escape: require('./$.replacer')(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); },{"./$.def":13,"./$.replacer":26}],73:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON require('./$.collection-to-json')('Set'); },{"./$.collection-to-json":9}],74:[function(require,module,exports){ // https://github.com/mathiasbynens/String.prototype.at var $def = require('./$.def'); $def($def.P, 'String', { at: require('./$.string-at')(true) }); },{"./$.def":13,"./$.string-at":29}],75:[function(require,module,exports){ // JavaScript 1.6 / Strawman array statics shim var $ = require('./$') , $def = require('./$.def') , $Array = $.core.Array || Array , statics = {}; function setStatics(keys, length){ $.each.call(keys.split(','), function(key){ if(length == undefined && key in $Array)statics[key] = $Array[key]; else if(key in [])statics[key] = require('./$.ctx')(Function.call, [][key], length); }); } setStatics('pop,reverse,shift,keys,values,entries', 1); setStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3); setStatics('join,slice,concat,push,splice,unshift,sort,lastIndexOf,' + 'reduce,reduceRight,copyWithin,fill,turn'); $def($def.S, 'Array', statics); },{"./$":22,"./$.ctx":12,"./$.def":13}],76:[function(require,module,exports){ require('./es6.array.iterator'); var $ = require('./$') , Iterators = require('./$.iter').Iterators , ITERATOR = require('./$.wks')('iterator') , ArrayValues = Iterators.Array , NodeList = $.g.NodeList; if($.FW && NodeList && !(ITERATOR in NodeList.prototype)){ $.hide(NodeList.prototype, ITERATOR, ArrayValues); } Iterators.NodeList = ArrayValues; },{"./$":22,"./$.iter":21,"./$.wks":33,"./es6.array.iterator":40}],77:[function(require,module,exports){ var $def = require('./$.def') , $task = require('./$.task'); $def($def.G + $def.B, { setImmediate: $task.set, clearImmediate: $task.clear }); },{"./$.def":13,"./$.task":30}],78:[function(require,module,exports){ // ie9- setTimeout & setInterval additional parameters fix var $ = require('./$') , $def = require('./$.def') , invoke = require('./$.invoke') , partial = require('./$.partial') , navigator = $.g.navigator , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke( partial, [].slice.call(arguments, 2), $.isFunction(fn) ? fn : Function(fn) ), time); } : set; } $def($def.G + $def.B + $def.F * MSIE, { setTimeout: wrap($.g.setTimeout), setInterval: wrap($.g.setInterval) }); },{"./$":22,"./$.def":13,"./$.invoke":17,"./$.partial":25}],79:[function(require,module,exports){ require('./modules/es5'); require('./modules/es6.symbol'); require('./modules/es6.object.assign'); require('./modules/es6.object.is'); require('./modules/es6.object.set-prototype-of'); require('./modules/es6.object.to-string'); require('./modules/es6.object.statics-accept-primitives'); require('./modules/es6.function.name'); require('./modules/es6.number.constructor'); require('./modules/es6.number.statics'); require('./modules/es6.math'); require('./modules/es6.string.from-code-point'); require('./modules/es6.string.raw'); require('./modules/es6.string.iterator'); require('./modules/es6.string.code-point-at'); require('./modules/es6.string.ends-with'); require('./modules/es6.string.includes'); require('./modules/es6.string.repeat'); require('./modules/es6.string.starts-with'); require('./modules/es6.array.from'); require('./modules/es6.array.of'); require('./modules/es6.array.iterator'); require('./modules/es6.array.species'); require('./modules/es6.array.copy-within'); require('./modules/es6.array.fill'); require('./modules/es6.array.find'); require('./modules/es6.array.find-index'); require('./modules/es6.regexp'); require('./modules/es6.promise'); require('./modules/es6.map'); require('./modules/es6.set'); require('./modules/es6.weak-map'); require('./modules/es6.weak-set'); require('./modules/es6.reflect'); require('./modules/es7.array.includes'); require('./modules/es7.string.at'); require('./modules/es7.regexp.escape'); require('./modules/es7.object.get-own-property-descriptors'); require('./modules/es7.object.to-array'); require('./modules/es7.map.to-json'); require('./modules/es7.set.to-json'); require('./modules/js.array.statics'); require('./modules/web.timers'); require('./modules/web.immediate'); require('./modules/web.dom.iterable'); module.exports = require('./modules/$').core; },{"./modules/$":22,"./modules/es5":34,"./modules/es6.array.copy-within":35,"./modules/es6.array.fill":36,"./modules/es6.array.find":38,"./modules/es6.array.find-index":37,"./modules/es6.array.from":39,"./modules/es6.array.iterator":40,"./modules/es6.array.of":41,"./modules/es6.array.species":42,"./modules/es6.function.name":43,"./modules/es6.map":44,"./modules/es6.math":45,"./modules/es6.number.constructor":46,"./modules/es6.number.statics":47,"./modules/es6.object.assign":48,"./modules/es6.object.is":49,"./modules/es6.object.set-prototype-of":50,"./modules/es6.object.statics-accept-primitives":51,"./modules/es6.object.to-string":52,"./modules/es6.promise":53,"./modules/es6.reflect":54,"./modules/es6.regexp":55,"./modules/es6.set":56,"./modules/es6.string.code-point-at":57,"./modules/es6.string.ends-with":58,"./modules/es6.string.from-code-point":59,"./modules/es6.string.includes":60,"./modules/es6.string.iterator":61,"./modules/es6.string.raw":62,"./modules/es6.string.repeat":63,"./modules/es6.string.starts-with":64,"./modules/es6.symbol":65,"./modules/es6.weak-map":66,"./modules/es6.weak-set":67,"./modules/es7.array.includes":68,"./modules/es7.map.to-json":69,"./modules/es7.object.get-own-property-descriptors":70,"./modules/es7.object.to-array":71,"./modules/es7.regexp.escape":72,"./modules/es7.set.to-json":73,"./modules/es7.string.at":74,"./modules/js.array.statics":75,"./modules/web.dom.iterable":76,"./modules/web.immediate":77,"./modules/web.timers":78}],80:[function(require,module,exports){ (function (process,global){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ !(function(global) { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var undefined; // More compressible than void 0. var iteratorSymbol = typeof Symbol === "function" && Symbol.iterator || "@@iterator"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided, then outerFn.prototype instanceof Generator. var generator = Object.create((outerFn || Generator).prototype); generator._invoke = makeInvokeMethod( innerFn, self || null, new Context(tryLocsList || []) ); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } runtime.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function(genFun) { genFun.__proto__ = GeneratorFunctionPrototype; genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `value instanceof AwaitArgument` to determine if the yielded value is // meant to be awaited. Some may consider the name of this method too // cutesy, but they are curmudgeons. runtime.awrap = function(arg) { return new AwaitArgument(arg); }; function AwaitArgument(arg) { this.arg = arg; } function AsyncIterator(generator) { // This invoke function is written in a style that assumes some // calling function (or Promise) will handle exceptions. function invoke(method, arg) { var result = generator[method](arg); var value = result.value; return value instanceof AwaitArgument ? Promise.resolve(value.arg).then(invokeNext, invokeThrow) : result; } if (typeof process === "object" && process.domain) { invoke = process.domain.bind(invoke); } var invokeNext = invoke.bind(generator, "next"); var invokeThrow = invoke.bind(generator, "throw"); var invokeReturn = invoke.bind(generator, "return"); var previousPromise; function enqueue(method, arg) { var enqueueResult = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then(function() { return invoke(method, arg); }) : new Promise(function(resolve) { resolve(invoke(method, arg)); }); // Avoid propagating enqueueResult failures to Promises returned by // later invocations of the iterator, and call generator.return() to // allow the generator a chance to clean up. previousPromise = enqueueResult.catch(invokeReturn); return enqueueResult; } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. runtime.async = function(innerFn, outerFn, self, tryLocsList) { var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList) ); return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } while (true) { var delegate = context.delegate; if (delegate) { if (method === "return" || (method === "throw" && delegate.iterator[method] === undefined)) { // A return or throw (when the delegate iterator has no throw // method) always terminates the yield* loop. context.delegate = null; // If the delegate iterator has a return method, give it a // chance to clean up. var returnMethod = delegate.iterator["return"]; if (returnMethod) { var record = tryCatch(returnMethod, delegate.iterator, arg); if (record.type === "throw") { // If the return method threw an exception, let that // exception prevail over the original return or throw. method = "throw"; arg = record.arg; continue; } } if (method === "return") { // Continue with the outer return, now that the delegate // iterator has been terminated. continue; } } var record = tryCatch( delegate.iterator[method], delegate.iterator, arg ); if (record.type === "throw") { context.delegate = null; // Like returning generator.throw(uncaught), but without the // overhead of an extra function call. method = "throw"; arg = record.arg; continue; } // Delegate generator ran and handled its own exceptions so // regardless of what the method was, we continue as if it is // "next" with an undefined arg. method = "next"; arg = undefined; var info = record.arg; if (info.done) { context[delegate.resultName] = info.value; context.next = delegate.nextLoc; } else { state = GenStateSuspendedYield; return info; } context.delegate = null; } if (method === "next") { if (state === GenStateSuspendedYield) { context.sent = arg; } else { delete context.sent; } } else if (method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw arg; } if (context.dispatchException(arg)) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. method = "next"; arg = undefined; } } else if (method === "return") { context.abrupt("return", arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; var info = { value: record.arg, done: context.done }; if (record.arg === ContinueSentinel) { if (context.delegate && method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. arg = undefined; } } else { return info; } } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(arg) call above. method = "throw"; arg = record.arg; } } }; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(); } runtime.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function() { this.prev = 0; this.next = 0; this.sent = undefined; this.done = false; this.delegate = null; this.tryEntries.forEach(resetTryEntry); // Pre-initialize at least 20 temporary variables to enable hidden // class optimizations for simple generators. for (var tempIndex = 0, tempName; hasOwn.call(this, tempName = "t" + tempIndex) || tempIndex < 20; ++tempIndex) { this[tempName] = null; } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; return !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.next = finallyEntry.finallyLoc; } else { this.complete(record); } return ContinueSentinel; }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = record.arg; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; return ContinueSentinel; } }; })( // Among the various tricks for obtaining a reference to the global // object, this seems to be the most reliable technique that does not // use indirect eval (which violates Content Security Policy). typeof global === "object" ? global : typeof window === "object" ? window : typeof self === "object" ? self : this ); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":2}]},{},[1]);
packages/mui-icons-material/lib/esm/SortSharp.js
oliviertassinari/material-ui
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M3 18h6v-2H3v2zM3 6v2h18V6H3zm0 7h12v-2H3v2z" }), 'SortSharp');
packages/core/email/admin/src/pages/Settings/components/EmailHeader.js
wistityhq/strapi
import React from 'react'; import { useIntl } from 'react-intl'; import { SettingsPageTitle } from '@strapi/helper-plugin'; import { HeaderLayout } from '@strapi/design-system/Layout'; import getTrad from '../../../utils/getTrad'; const EmailHeader = () => { const { formatMessage } = useIntl(); return ( <> <SettingsPageTitle name={formatMessage({ id: getTrad('Settings.email.plugin.title'), defaultMessage: 'Configuration', })} /> <HeaderLayout id="title" title={formatMessage({ id: getTrad('Settings.email.plugin.title'), defaultMessage: 'Configuration', })} subtitle={formatMessage({ id: getTrad('Settings.email.plugin.subTitle'), defaultMessage: 'Test the settings for the Email plugin', })} /> </> ); }; export default EmailHeader;
chrome/extension/todoapp.js
meth-makers/dolphin
import React from 'react'; import ReactDOM from 'react-dom'; import Root from '../../app/containers/Root'; import './todoapp.css'; chrome.storage.local.get('state', obj => { const { state } = obj; const initialState = JSON.parse(state || '{}'); const createStore = require('../../app/store/configureStore'); ReactDOM.render( <Root store={createStore(initialState)} />, document.querySelector('#root') ); });
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/node_modules/rc-calendar/es/month/MonthPanel.js
bhathiya/test
import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import YearPanel from '../year/YearPanel'; import MonthTable from './MonthTable'; function goYear(direction) { var next = this.state.value.clone(); next.add(direction, 'year'); this.setAndChangeValue(next); } function noop() {} var MonthPanel = createReactClass({ displayName: 'MonthPanel', propTypes: { onChange: PropTypes.func, disabledDate: PropTypes.func, onSelect: PropTypes.func }, getDefaultProps: function getDefaultProps() { return { onChange: noop, onSelect: noop }; }, getInitialState: function getInitialState() { var props = this.props; // bind methods this.nextYear = goYear.bind(this, 1); this.previousYear = goYear.bind(this, -1); this.prefixCls = props.rootPrefixCls + '-month-panel'; return { value: props.value || props.defaultValue }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if ('value' in nextProps) { this.setState({ value: nextProps.value }); } }, onYearPanelSelect: function onYearPanelSelect(current) { this.setState({ showYearPanel: 0 }); this.setAndChangeValue(current); }, setAndChangeValue: function setAndChangeValue(value) { this.setValue(value); this.props.onChange(value); }, setAndSelectValue: function setAndSelectValue(value) { this.setValue(value); this.props.onSelect(value); }, setValue: function setValue(value) { if (!('value' in this.props)) { this.setState({ value: value }); } }, showYearPanel: function showYearPanel() { this.setState({ showYearPanel: 1 }); }, render: function render() { var props = this.props; var value = this.state.value; var cellRender = props.cellRender; var contentRender = props.contentRender; var locale = props.locale; var year = value.year(); var prefixCls = this.prefixCls; var yearPanel = void 0; if (this.state.showYearPanel) { yearPanel = React.createElement(YearPanel, { locale: locale, value: value, rootPrefixCls: props.rootPrefixCls, onSelect: this.onYearPanelSelect }); } return React.createElement( 'div', { className: prefixCls, style: props.style }, React.createElement( 'div', null, React.createElement( 'div', { className: prefixCls + '-header' }, React.createElement('a', { className: prefixCls + '-prev-year-btn', role: 'button', onClick: this.previousYear, title: locale.previousYear }), React.createElement( 'a', { className: prefixCls + '-year-select', role: 'button', onClick: this.showYearPanel, title: locale.yearSelect }, React.createElement( 'span', { className: prefixCls + '-year-select-content' }, year ), React.createElement( 'span', { className: prefixCls + '-year-select-arrow' }, 'x' ) ), React.createElement('a', { className: prefixCls + '-next-year-btn', role: 'button', onClick: this.nextYear, title: locale.nextYear }) ), React.createElement( 'div', { className: prefixCls + '-body' }, React.createElement(MonthTable, { disabledDate: props.disabledDate, onSelect: this.setAndSelectValue, locale: locale, value: value, cellRender: cellRender, contentRender: contentRender, prefixCls: prefixCls }) ) ), yearPanel ); } }); export default MonthPanel;
src/svg-icons/device/screen-lock-rotation.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceScreenLockRotation = (props) => ( <SvgIcon {...props}> <path d="M23.25 12.77l-2.57-2.57-1.41 1.41 2.22 2.22-5.66 5.66L4.51 8.17l5.66-5.66 2.1 2.1 1.41-1.41L11.23.75c-.59-.59-1.54-.59-2.12 0L2.75 7.11c-.59.59-.59 1.54 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12zM8.47 20.48C5.2 18.94 2.86 15.76 2.5 12H1c.51 6.16 5.66 11 11.95 11l.66-.03-3.81-3.82-1.33 1.33zM16 9h5c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1v-.5C21 1.12 19.88 0 18.5 0S16 1.12 16 2.5V3c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1zm.8-6.5c0-.94.76-1.7 1.7-1.7s1.7.76 1.7 1.7V3h-3.4v-.5z"/> </SvgIcon> ); DeviceScreenLockRotation = pure(DeviceScreenLockRotation); DeviceScreenLockRotation.displayName = 'DeviceScreenLockRotation'; DeviceScreenLockRotation.muiName = 'SvgIcon'; export default DeviceScreenLockRotation;
src/utils/messageParser.js
svmn/ace-fnd
'use strict'; import React from 'react'; import replacer from 'react-string-replace'; import { LINK_REGEXP, REPLY_REGEXP, MARKUP_STRONG_REGEXP, MARKUP_EMPH_REGEXP, MARKUP_STRIKE_REGEXP, MARKUP_SPOILER_REGEXP, MARKUP_QUOTE_REGEXP, MARKUP_ADM_REGEXP, MARKUP_MOD_REGEXP, YOUTUBE_REPLACE_REGEXP, PRIVATE_REGEXP } from '../constants'; export function parseMarkup(text) { let replaced = replacer(text, MARKUP_QUOTE_REGEXP, (match, i) => ( <span className='quote' key={`quote${i}`}>{match}</span> )); replaced = replacer(replaced, MARKUP_STRONG_REGEXP, (match, i) => ( <span className='strong' key={`strong${i}`}>{match}</span> )); replaced = replacer(replaced, MARKUP_EMPH_REGEXP, (match, i) => ( <span className='emph' key={`emph${i}`}>{match}</span> )); replaced = replacer(replaced, MARKUP_SPOILER_REGEXP, (match, i) => ( <span className='spoiler' key={`spoiler${i}`}>{match}</span> )); replaced = replacer(replaced, MARKUP_STRIKE_REGEXP, (match, i) => ( <span className='strike' key={`strike${i}`}>{match}</span> )); replaced = replacer(replaced, MARKUP_ADM_REGEXP, (match, i) => ( <span style={{ color: 'red' }} key={`adm${i}`}>Admin</span> )); replaced = replacer(replaced, MARKUP_MOD_REGEXP, (match, i) => ( <span style={{ color: 'blue' }} key={`mod${i}`}>Moderator</span> )); return replaced; } export function parseReplies(text, onTouchTap, onMouseEnter, onMouseMove, onMouseLeave) { const replaced = replacer(text, REPLY_REGEXP, (match, i) => ( <a href='' key={`r${i}`} onClick={e => e.preventDefault()} onTouchTap={() => onTouchTap(match)} onMouseEnter={() => onMouseEnter(match)} onMouseMove={onMouseMove} onMouseLeave={onMouseLeave} > @{match} </a> )); return replacer(replaced, PRIVATE_REGEXP, (match, i) => ( <a href='' key={`p${i}`} onClick={e => e.preventDefault()} onTouchTap={() => onTouchTap(match)} > !#{match} </a> )); } export function parseLinks(text) { return replacer(text, LINK_REGEXP, (match, i) => ( <a href={match} target='_blank' key={`link${i}`}>{match}</a> )); } export function replaceYoutubeLink(text, title) { return replacer(text, YOUTUBE_REPLACE_REGEXP, (match, i) => ( <a href={match} target='_blank' key={`youtube${i}`}>{title}</a> )); }
__tests__/index.android.js
Blacktoviche/RNChat
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
nailgun/static/views/cluster_page_tabs/healthcheck_tab.js
eayunstack/fuel-web
/* * Copyright 2014 Mirantis, Inc. * * Licensed under the Apache License, Version 2.0 (the 'License'); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ import $ from 'jquery'; import _ from 'underscore'; import i18n from 'i18n'; import Backbone from 'backbone'; import React from 'react'; import utils from 'utils'; import models from 'models'; import {Input} from 'views/controls'; import {backboneMixin, pollingMixin} from 'component_mixins'; var HealthCheckTab = React.createClass({ mixins: [ backboneMixin({ modelOrCollection: (props) => props.cluster.get('tasks'), renderOn: 'update change:status' }), backboneMixin('cluster', 'change:status') ], statics: { fetchData(options) { if (!options.cluster.get('ostf')) { var ostf = {}; var clusterId = options.cluster.id; ostf.testsets = new models.TestSets(); ostf.testsets.url = _.result(ostf.testsets, 'url') + '/' + clusterId; ostf.tests = new models.Tests(); ostf.tests.url = _.result(ostf.tests, 'url') + '/' + clusterId; ostf.testruns = new models.TestRuns(); ostf.testruns.url = _.result(ostf.testruns, 'url') + '/last/' + clusterId; return $.when(ostf.testsets.fetch(), ostf.tests.fetch(), ostf.testruns.fetch()).then(() => { options.cluster.set({ostf: ostf}); return {}; }, () => $.Deferred().resolve() ); } return $.Deferred().resolve(); } }, render() { var ostf = this.props.cluster.get('ostf'); return ( <div className='row'> <div className='title'> {i18n('cluster_page.healthcheck_tab.title')} </div> <div className='col-xs-12 content-elements'> {ostf ? <HealthcheckTabContent ref='content' testsets={ostf.testsets} tests={ostf.tests} testruns={ostf.testruns} cluster={this.props.cluster} /> : <div className='alert alert-danger'> {i18n('cluster_page.healthcheck_tab.not_available_alert')} </div> } </div> </div> ); } }); var HealthcheckTabContent = React.createClass({ mixins: [ backboneMixin('tests', 'update change'), backboneMixin('testsets', 'update change:checked'), backboneMixin('testruns', 'update change'), pollingMixin(3) ], shouldDataBeFetched() { return this.props.testruns.any({status: 'running'}); }, fetchData() { return this.props.testruns.fetch(); }, getInitialState() { return { actionInProgress: false, credentialsVisible: null, credentials: _.transform(this.props.cluster.get('settings').get('access'), (result, value, key) => { result[key] = value.value; }) }; }, isLocked() { var cluster = this.props.cluster; return cluster.get('status') != 'operational' || !!cluster.task({group: 'deployment', active: true}); }, getNumberOfCheckedTests() { return this.props.tests.where({checked: true}).length; }, toggleCredentials() { this.setState({credentialsVisible: !this.state.credentialsVisible}); }, handleSelectAllClick(name, value) { this.props.tests.invoke('set', {checked: value}); }, handleInputChange(name, value) { var credentials = this.state.credentials; credentials[name] = value; this.setState({credentials: credentials}); }, runTests() { var testruns = new models.TestRuns(); var oldTestruns = new models.TestRuns(); var testsetIds = this.props.testsets.pluck('id'); this.setState({actionInProgress: true}); _.each(testsetIds, (testsetId) => { var testsToRun = _.pluck(this.props.tests.where({ testset: testsetId, checked: true }), 'id'); if (testsToRun.length) { var testrunConfig = {tests: testsToRun}; var addCredentials = (obj) => { obj.ostf_os_access_creds = { ostf_os_username: this.state.credentials.user, ostf_os_tenant_name: this.state.credentials.tenant, ostf_os_password: this.state.credentials.password }; return obj; }; if (this.props.testruns.where({testset: testsetId}).length) { _.each(this.props.testruns.where({testset: testsetId}), (testrun) => { _.extend(testrunConfig, addCredentials({ id: testrun.id, status: 'restarted' })); oldTestruns.add(new models.TestRun(testrunConfig)); }, this); } else { _.extend(testrunConfig, { testset: testsetId, metadata: addCredentials({ config: {}, cluster_id: this.props.cluster.id }) }); testruns.add(new models.TestRun(testrunConfig)); } } }); var requests = []; if (testruns.length) { requests.push(Backbone.sync('create', testruns)); } if (oldTestruns.length) { requests.push(Backbone.sync('update', oldTestruns)); } $.when(...requests) .done(() => { this.startPolling(true); }) .fail((response) => { utils.showErrorDialog({response: response}); }) .always(() => { this.setState({actionInProgress: false}); }); }, getActiveTestRuns() { return this.props.testruns.where({status: 'running'}); }, stopTests() { var testruns = new models.TestRuns(this.getActiveTestRuns()); if (testruns.length) { this.setState({actionInProgress: true}); testruns.invoke('set', {status: 'stopped'}); testruns.toJSON = function() { return this.map((testrun) => _.pick(testrun.attributes, 'id', 'status') ); }; Backbone.sync('update', testruns).done(() => { this.setState({actionInProgress: false}); this.startPolling(true); }); } }, render() { var disabledState = this.isLocked(); var hasRunningTests = !!this.props.testruns.where({status: 'running'}).length; return ( <div> {!disabledState && <div className='healthcheck-controls row well well-sm'> <div className='pull-left'> <Input type='checkbox' name='selectAll' onChange={this.handleSelectAllClick} checked={this.getNumberOfCheckedTests() == this.props.tests.length} disabled={hasRunningTests} label={i18n('common.select_all')} wrapperClassName='select-all' /> </div> {hasRunningTests ? (<button className='btn btn-danger stop-tests-btn pull-right' disabled={this.state.actionInProgress} onClick={this.stopTests} > {i18n('cluster_page.healthcheck_tab.stop_tests_button')} </button>) : (<button className='btn btn-success run-tests-btn pull-right' disabled={!this.getNumberOfCheckedTests() || this.state.actionInProgress} onClick={this.runTests} > {i18n('cluster_page.healthcheck_tab.run_tests_button')} </button>) } <button className='btn btn-default toggle-credentials pull-right' data-toggle='collapse' data-target='.credentials' onClick={this.toggleCredentials} > {i18n('cluster_page.healthcheck_tab.provide_credentials')} </button> <HealthcheckCredentials credentials={this.state.credentials} onInputChange={this.handleInputChange} disabled={hasRunningTests} /> </div> } <div> {(this.props.cluster.get('status') == 'new') && <div className='alert alert-warning'>{i18n('cluster_page.healthcheck_tab.deploy_alert')}</div> } <div key='testsets'> {this.props.testsets.map((testset) => { return <TestSet key={testset.id} testset={testset} testrun={this.props.testruns.findWhere({testset: testset.id}) || new models.TestRun({testset: testset.id})} tests={new Backbone.Collection(this.props.tests.where({testset: testset.id}))} disabled={disabledState || hasRunningTests} />; })} </div> </div> </div> ); } }); var HealthcheckCredentials = React.createClass({ render() { var inputFields = ['user', 'password', 'tenant']; return ( <div className='credentials collapse col-xs-12'> <div className='forms-box'> <div className='alert alert-warning'> {i18n('cluster_page.healthcheck_tab.credentials_description')} </div> {_.map(inputFields, (name) => { return (<Input key={name} type={(name == 'password') ? 'password' : 'text'} name={name} label={i18n('cluster_page.healthcheck_tab.' + name + '_label')} value={this.props.credentials[name]} onChange={this.props.onInputChange} toggleable={name == 'password'} description={i18n('cluster_page.healthcheck_tab.' + name + '_description')} disabled={this.props.disabled} inputClassName='col-xs-3' />); })} </div> </div> ); } }); var TestSet = React.createClass({ mixins: [ backboneMixin('tests'), backboneMixin('testset') ], handleTestSetCheck(name, value) { this.props.testset.set('checked', value); this.props.tests.invoke('set', {checked: value}); }, componentWillUnmount() { this.props.tests.invoke('off', 'change:checked', this.updateTestsetCheckbox, this); }, componentWillMount() { this.props.tests.invoke('on', 'change:checked', this.updateTestsetCheckbox, this); }, updateTestsetCheckbox() { this.props.testset.set('checked', this.props.tests.where({checked: true}).length == this.props.tests.length); }, render() { var classes = { 'table healthcheck-table': true, disabled: this.props.disabled }; return ( <table className={utils.classNames(classes)}> <thead> <tr> <th> <Input type='checkbox' id={'testset-checkbox-' + this.props.testset.id} name={this.props.testset.get('name')} disabled={this.props.disabled} onChange={this.handleTestSetCheck} checked={this.props.testset.get('checked')} /> </th> <th className='col-xs-7 healthcheck-name'> <label htmlFor={'testset-checkbox-' + this.props.testset.id}> {this.props.testset.get('name')} </label> </th> <th className='healthcheck-col-duration col-xs-2'> {i18n('cluster_page.healthcheck_tab.expected_duration')} </th> <th className='healthcheck-col-duration col-xs-2'> {i18n('cluster_page.healthcheck_tab.actual_duration')} </th> <th className='healthcheck-col-status col-xs-1'> {i18n('cluster_page.healthcheck_tab.status')} </th> </tr> </thead> <tbody> {this.props.tests.map((test) => { var result = this.props.testrun && _.find(this.props.testrun.get('tests'), {id: test.id}); var status = result && result.status || 'unknown'; return <Test key={test.id} test={test} result={result} status={status} disabled={this.props.disabled} />; })} </tbody> </table> ); } }); var Test = React.createClass({ mixins: [ backboneMixin('test') ], handleTestCheck(name, value) { this.props.test.set('checked', value); }, render() { var test = this.props.test; var result = this.props.result; var description = _.escape(_.trim(test.get('description'))); var status = this.props.status; var currentStatusClassName = 'text-center healthcheck-status healthcheck-status-' + status; var iconClasses = { success: 'glyphicon glyphicon-ok text-success', failure: 'glyphicon glyphicon-remove text-danger', error: 'glyphicon glyphicon-remove text-danger', running: 'glyphicon glyphicon-refresh animate-spin', wait_running: 'glyphicon glyphicon-time' }; return ( <tr> <td> <Input type='checkbox' id={'test-checkbox-' + test.id} name={test.get('name')} disabled={this.props.disabled} onChange={this.handleTestCheck} checked={test.get('checked')} /> </td> <td className='healthcheck-name'> <label htmlFor={'test-checkbox-' + test.id}>{test.get('name')}</label> {_.contains(['failure', 'error', 'skipped'], status) && <div className='text-danger'> {(result && result.message) && <div> <b>{result.message}</b> </div> } <div className='well' dangerouslySetInnerHTML={{__html: utils.urlify( (result && _.isNumber(result.step)) ? utils.highlightTestStep(description, result.step) : description ) }}> </div> </div> } </td> <td className='healthcheck-col-duration'> <div className='healthcheck-duration'>{test.get('duration') || ''}</div> </td> <td className='healthcheck-col-duration'> {(status != 'running' && result && _.isNumber(result.taken)) ? <div className='healthcheck-duration'>{result.taken.toFixed(1)}</div> : <div className='healthcheck-status healthcheck-status-unknown'>&mdash;</div> } </td> <td className='healthcheck-col-status'> <div className={currentStatusClassName}> {iconClasses[status] ? <i className={iconClasses[status]} /> : String.fromCharCode(0x2014)} </div> </td> </tr> ); } }); export default HealthCheckTab;
examples/src/components/CustomRenderField.js
katienreed/react-select
import React from 'react'; import Select from 'react-select'; function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } var CustomRenderField = React.createClass({ displayName: 'CustomRenderField', propTypes: { delimiter: React.PropTypes.string, label: React.PropTypes.string, multi: React.PropTypes.bool, }, renderOption (option) { return <span style={{ color: option.hex }}>{option.label} ({option.hex})</span>; }, renderValue (option) { return <strong style={{ color: option.hex }}>{option.label}</strong>; }, render () { var ops = [ { label: 'Red', value: 'red', hex: '#EC6230' }, { label: 'Green', value: 'green', hex: '#4ED84E' }, { label: 'Blue', value: 'blue', hex: '#6D97E2' } ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select delimiter={this.props.delimiter} multi={this.props.multi} allowCreate={true} placeholder="Select your favourite" options={ops} optionRenderer={this.renderOption} valueRenderer={this.renderValue} onChange={logChange} /> </div> ); } }); module.exports = CustomRenderField;
features/hocs/withLayout.js
nlambert/checkin
import React from 'react'; import * as layouts from '../layouts'; const withLayout = (layoutName = 'Main') => Body => { const Layout = layouts[layoutName]; const WithLayout = props => ( <Layout { ...props }> <Body { ...props } /> </Layout> ); return WithLayout; }; export default withLayout;
entry_types/scrolled/package/spec/frontend/MotifArea-spec.js
codevise/pageflow
import React from 'react'; import '@testing-library/jest-dom/extend-expect' import {renderInEntry} from 'support'; import {useFile} from 'entryState'; import {useBackgroundFile} from 'frontend/useBackgroundFile'; import {MotifArea, MotifAreaVisibilityProvider} from 'frontend/MotifArea'; import styles from 'frontend/MotifArea.module.css'; describe('MotifArea', () => { it('positions element based on motif area passed to useBackgroundFile', () => { const {container} = renderInEntry( () => { const file = useBackgroundFile({ file: useFile({collectionName: 'imageFiles', permaId: 100}), motifArea: {top: 10, left: 10, width: 50, height: 50}, containerDimension: {width: 2000, height: 1000} }); return ( <MotifArea file={file} /> ); }, { seed: { imageFiles: [ { permaId: 100, width: 200, height: 100 } ] } } ); expect(container.firstChild).toHaveStyle('top: 100px'); expect(container.firstChild).toHaveStyle('left: 200px'); expect(container.firstChild).toHaveStyle('width: 1000px'); expect(container.firstChild).toHaveStyle('height: 500px'); }); it('renders nothing when file is not set', () => { const {container} = renderInEntry( <MotifArea file={null} containerWidth={2000} containerHeight={1000}/> ); expect(container.firstChild).toBeNull(); }); it('renders nothing when file is not ready', () => { const {container} = renderInEntry( () => <MotifArea file={useFile({collectionName: 'imageFiles', permaId: 100})} />, { seed: { imageFiles: [ { permaId: 100, isReady: false } ] } } ); expect(container.firstChild).toBeNull(); }); it('renders zero size element when image does not have motif area', () => { const {container} = renderInEntry( () => <MotifArea file={useFile({collectionName: 'imageFiles', permaId: 100})} />, { seed: { imageFiles: [ { permaId: 100, width: 200, height: 100 } ] } } ); expect(container.firstChild).toHaveStyle('top: 0px'); expect(container.firstChild).toHaveStyle('left: 0px'); expect(container.firstChild).toHaveStyle('width: 0px'); expect(container.firstChild).toHaveStyle('height: 0px'); }); describe('onUpdate prop', () => { const seed = { imageFiles: [ { permaId: 100, width: 200, height: 100, configuration: { motifArea: { top: 10, left: 10, width: 50, height: 50 } } }, { permaId: 101, width: 200, height: 100, configuration: { motifArea: { top: 20, left: 20, width: 100, height: 100 } } } ] }; function useBackgroundFileByPermaId(permaId, {motifArea} = {}) { return useBackgroundFile({ file: useFile({collectionName: 'imageFiles', permaId}), containerDimension: {width: 2000, height: 1000}, motifArea }); } it('is called with element on render', () => { const callback = jest.fn(); const {container} = renderInEntry( () => <MotifArea file={useBackgroundFileByPermaId(100)} onUpdate={callback} />, {seed} ); expect(callback).toHaveBeenCalledWith(container.firstChild); }); it('is not called when rerendering without changing position', () => { const callback = jest.fn(); const {rerender} = renderInEntry( () => <MotifArea file={useBackgroundFileByPermaId(100)} onUpdate={callback} />, {seed} ); rerender( () => <MotifArea file={useBackgroundFileByPermaId(100)} onUpdate={callback} /> ); expect(callback).toHaveBeenCalledTimes(1); }); it('is called when position changes', () => { const callback = jest.fn(); const {container, rerender} = renderInEntry( () => <MotifArea file={useBackgroundFileByPermaId(100, {motifArea: { top: 10, left: 10, width: 50, height: 50 }})} onUpdate={callback} />, {seed} ); callback.mockReset(); rerender( () => <MotifArea file={useBackgroundFileByPermaId(101, {motifArea: { top: 20, left: 20, width: 100, height: 100 }})} onUpdate={callback} /> ); expect(callback).toHaveBeenCalledWith(container.firstChild); }); it('is not called when image is not set', () => { const callback = jest.fn(); renderInEntry( () => <MotifArea file={null} onUpdate={callback} />, {seed} ); expect(callback).not.toHaveBeenCalled(); }); }); it('makes motif area visible if rendered inside MotifAreaVisibilityProvider', () => { const {container} = renderInEntry( () => { const file = useBackgroundFile({ file: useFile({collectionName: 'imageFiles', permaId: 100}), motifArea: {top: 10, left: 10, width: 50, height: 50}, containerDimension: {width: 2000, height: 1000} }); return ( <MotifArea file={file} /> ); }, { wrapper: ({children}) => ( <MotifAreaVisibilityProvider visible={true}> {children} </MotifAreaVisibilityProvider> ), seed: { imageFiles: [ { permaId: 100, width: 200, height: 100 } ] } } ); expect(container.firstChild).toHaveClass(styles.visible); }); });
app/javascript/mastodon/features/ui/components/confirmation_modal.js
lindwurm/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, FormattedMessage } from 'react-intl'; import Button from '../../../components/button'; export default @injectIntl class ConfirmationModal extends React.PureComponent { static propTypes = { message: PropTypes.node.isRequired, confirm: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, onConfirm: PropTypes.func.isRequired, secondary: PropTypes.string, onSecondary: PropTypes.func, closeWhenConfirm: PropTypes.bool, intl: PropTypes.object.isRequired, }; static defaultProps = { closeWhenConfirm: true, }; componentDidMount() { this.button.focus(); } handleClick = () => { if (this.props.closeWhenConfirm) { this.props.onClose(); } this.props.onConfirm(); } handleSecondary = () => { this.props.onClose(); this.props.onSecondary(); } handleCancel = () => { this.props.onClose(); } setRef = (c) => { this.button = c; } render () { const { message, confirm, secondary } = this.props; return ( <div className='modal-root__modal confirmation-modal'> <div className='confirmation-modal__container'> {message} </div> <div className='confirmation-modal__action-bar'> <Button onClick={this.handleCancel} className='confirmation-modal__cancel-button'> <FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' /> </Button> {secondary !== undefined && ( <Button text={secondary} onClick={this.handleSecondary} className='confirmation-modal__secondary-button' /> )} <Button text={confirm} onClick={this.handleClick} ref={this.setRef} /> </div> </div> ); } }
app/containers/AboutPage.js
luismreis/bootstrap-starter-template-react
import React, { Component } from 'react'; export default class AboutPage extends Component { render() { return ( <div className="about"> <h1>About</h1> </div> ); } }
app/javascript/mastodon/features/blocks/index.js
dunn/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import PropTypes from 'prop-types'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import AccountContainer from '../../containers/account_container'; import { fetchBlocks, expandBlocks } from '../../actions/blocks'; import ScrollableList from '../../components/scrollable_list'; const messages = defineMessages({ heading: { id: 'column.blocks', defaultMessage: 'Blocked users' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'blocks', 'items']), hasMore: !!state.getIn(['user_lists', 'blocks', 'next']), }); export default @connect(mapStateToProps) @injectIntl class Blocks extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, accountIds: ImmutablePropTypes.list, hasMore: PropTypes.bool, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchBlocks()); } handleLoadMore = debounce(() => { this.props.dispatch(expandBlocks()); }, 300, { leading: true }); render () { const { intl, accountIds, shouldUpdateScroll, hasMore, multiColumn } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.blocks' defaultMessage="You haven't blocked any users yet." />; return ( <Column bindToDocument={!multiColumn} icon='ban' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollableList scrollKey='blocks' onLoadMore={this.handleLoadMore} hasMore={hasMore} shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} bindToDocument={!multiColumn} > {accountIds.map(id => <AccountContainer key={id} id={id} /> )} </ScrollableList> </Column> ); } }
ext/tilt-react.js
jphastings/tilt-react
import React from 'react'; import ReactDOM from 'react-dom'; class TiltReactClass { constructor() { this.components = {}; } bind() { this.reactContainers().forEach(container => { const componentName = container.dataset.reactClass; const propsContainer = container.nextElementSibling; const props = JSON.parse(propsContainer.innerText); this.render(container, componentName, props); container.parentElement.removeChild(propsContainer); }); window.addEventListener('popstate', event => { const containers = this.reactContainers(); try { event.state.forEach((data, i) => { this.render( containers[i], data[0], JSON.parse(data[1]) || {} ); }); } catch(e) { // State wasn't in the correct format } }); } render(container, componentName, props, pathChange) { const element = this.elementForComponent(componentName, props); ReactDOM.render(element, container); container.dataset.reactClass = componentName; container.dataset.props = JSON.stringify(props); if (typeof pathChange === 'undefined') { window.history.replaceState( this.pageState(), document.title, window.location.href ); } else { window.history.pushState( this.pageState(), document.title, pathChange ); } } elementForComponent(componentName, props) { const component = this.components[componentName]; const element = React.createElement(component, props); return element; } addComponent(component) { this.components[component.name] = component; } componentNames() { return Object.keys(this.components); } reactContainers() { return Array.prototype.slice.call(document.querySelectorAll('div[data-react-class]')); } reactContainerFor(element) { while(typeof element !== 'null') { if (element.hasAttribute('data-react-class')) { return element; } element = element.parentElement; } } pageState() { return this.reactContainers().map(container => { return [ container.dataset.reactClass, container.dataset.props ]; }); } fetch(path, options, targetContainer) { targetContainer = targetContainer || this.reactContainers()[0]; options = options || {}; options.headers = options.headers || {}; options.headers.Accept = 'application/json'; fetch(path, options).then(response => { return response.json(); }).then(json => { this.render(targetContainer, json[0], json[1], path); }); } ajaxLoad(event) { event.preventDefault(); switch(event.type) { case 'click': TiltReact.fetch( event.target.href, { method: 'GET' }, TiltReact.reactContainerFor(event.target) ); return; } } } window.TiltReact = new TiltReactClass(); module.exports = window.TiltReact;
node_modules/react-navigation/src/views/CardStack/CardStack.js
jiangqizheng/ReactNative-BookProject
/* @flow */ import React, { Component } from 'react'; import clamp from 'clamp'; import { Animated, StyleSheet, PanResponder, Platform, View, I18nManager, Easing, } from 'react-native'; import Card from './Card'; import Header from '../Header/Header'; import NavigationActions from '../../NavigationActions'; import addNavigationHelpers from '../../addNavigationHelpers'; import SceneView from '../SceneView'; import type { NavigationAction, NavigationLayout, NavigationScreenProp, NavigationScene, NavigationRouter, NavigationState, NavigationScreenDetails, NavigationStackScreenOptions, HeaderMode, ViewStyleProp, TransitionConfig, } from '../../TypeDefinition'; import TransitionConfigs from './TransitionConfigs'; const emptyFunction = () => {}; type Props = { screenProps?: {}, headerMode: HeaderMode, headerComponent?: ReactClass<*>, mode: 'card' | 'modal', navigation: NavigationScreenProp<NavigationState, NavigationAction>, router: NavigationRouter< NavigationState, NavigationAction, NavigationStackScreenOptions >, cardStyle?: ViewStyleProp, onTransitionStart?: () => void, onTransitionEnd?: () => void, style?: any, // TODO: Remove /** * Optional custom animation when transitioning between screens. */ transitionConfig?: () => TransitionConfig, // NavigationTransitionProps: layout: NavigationLayout, navigation: NavigationScreenProp<NavigationState, NavigationAction>, position: Animated.Value, progress: Animated.Value, scenes: Array<NavigationScene>, scene: NavigationScene, index: number, }; /** * The max duration of the card animation in milliseconds after released gesture. * The actual duration should be always less then that because the rest distance * is always less then the full distance of the layout. */ const ANIMATION_DURATION = 500; /** * The gesture distance threshold to trigger the back behavior. For instance, * `1/2` means that moving greater than 1/2 of the width of the screen will * trigger a back action */ const POSITION_THRESHOLD = 1 / 2; /** * The threshold (in pixels) to start the gesture action. */ const RESPOND_THRESHOLD = 20; /** * The distance of touch start from the edge of the screen where the gesture will be recognized */ const GESTURE_RESPONSE_DISTANCE_HORIZONTAL = 25; const GESTURE_RESPONSE_DISTANCE_VERTICAL = 135; const animatedSubscribeValue = (animatedValue: Animated.Value) => { if (!animatedValue.__isNative) { return; } if (Object.keys(animatedValue._listeners).length === 0) { animatedValue.addListener(emptyFunction); } }; class CardStack extends Component { /** * Used to identify the starting point of the position when the gesture starts, such that it can * be updated according to its relative position. This means that a card can effectively be * "caught"- If a gesture starts while a card is animating, the card does not jump into a * corresponding location for the touch. */ _gestureStartValue: number = 0; // tracks if a touch is currently happening _isResponding: boolean = false; /** * immediateIndex is used to represent the expected index that we will be on after a * transition. To achieve a smooth animation when swiping back, the action to go back * doesn't actually fire until the transition completes. The immediateIndex is used during * the transition so that gestures can be handled correctly. This is a work-around for * cases when the user quickly swipes back several times. */ _immediateIndex: ?number = null; _screenDetails: { [key: string]: ?NavigationScreenDetails<NavigationStackScreenOptions>, } = {}; props: Props; componentWillReceiveProps(props: Props) { if (props.screenProps !== this.props.screenProps) { this._screenDetails = {}; } props.scenes.forEach((newScene: *) => { if ( this._screenDetails[newScene.key] && this._screenDetails[newScene.key].state !== newScene.route ) { this._screenDetails[newScene.key] = null; } }); } _getScreenDetails = (scene: NavigationScene): NavigationScreenDetails<*> => { const { screenProps, navigation, router } = this.props; let screenDetails = this._screenDetails[scene.key]; if (!screenDetails || screenDetails.state !== scene.route) { const screenNavigation = addNavigationHelpers({ ...navigation, state: scene.route, }); screenDetails = { state: scene.route, navigation: screenNavigation, options: router.getScreenOptions(screenNavigation, screenProps), }; this._screenDetails[scene.key] = screenDetails; } return screenDetails; }; _renderHeader( scene: NavigationScene, headerMode: HeaderMode ): ?React.Element<*> { const { header } = this._getScreenDetails(scene).options; if (typeof header !== 'undefined' && typeof header !== 'function') { return header; } const renderHeader = header || ((props: *) => <Header {...props} />); // We need to explicitly exclude `mode` since Flow doesn't see // mode: headerMode override below and reports prop mismatch const { mode, ...passProps } = this.props; return renderHeader({ ...passProps, scene, mode: headerMode, getScreenDetails: this._getScreenDetails, }); } // eslint-disable-next-line class-methods-use-this _animatedSubscribe(props: Props) { // Hack to make this work with native driven animations. We add a single listener // so the JS value of the following animated values gets updated. We rely on // some Animated private APIs and not doing so would require using a bunch of // value listeners but we'd have to remove them to not leak and I'm not sure // when we'd do that with the current structure we have. `stopAnimation` callback // is also broken with native animated values that have no listeners so if we // want to remove this we have to fix this too. animatedSubscribeValue(props.layout.width); animatedSubscribeValue(props.layout.height); animatedSubscribeValue(props.position); } _reset(resetToIndex: number, duration: number): void { Animated.timing(this.props.position, { toValue: resetToIndex, duration, easing: Easing.linear(), useNativeDriver: this.props.position.__isNative, }).start(); } _goBack(backFromIndex: number, duration: number) { const { navigation, position, scenes } = this.props; const toValue = Math.max(backFromIndex - 1, 0); // set temporary index for gesture handler to respect until the action is // dispatched at the end of the transition. this._immediateIndex = toValue; Animated.timing(position, { toValue, duration, easing: Easing.linear(), useNativeDriver: position.__isNative, }).start(() => { this._immediateIndex = null; const backFromScene = scenes.find((s: *) => s.index === toValue + 1); if (!this._isResponding && backFromScene) { navigation.dispatch( NavigationActions.back({ key: backFromScene.route.key }) ); } }); } render(): React.Element<*> { let floatingHeader = null; const headerMode = this._getHeaderMode(); if (headerMode === 'float') { floatingHeader = this._renderHeader(this.props.scene, headerMode); } const { navigation, position, layout, scene, scenes, mode } = this.props; const { index } = navigation.state; const isVertical = mode === 'modal'; const responder = PanResponder.create({ onPanResponderTerminate: () => { this._isResponding = false; this._reset(index, 0); }, onPanResponderGrant: () => { position.stopAnimation((value: number) => { this._isResponding = true; this._gestureStartValue = value; }); }, onMoveShouldSetPanResponder: ( event: { nativeEvent: { pageY: number, pageX: number } }, gesture: any ) => { if (index !== scene.index) { return false; } const immediateIndex = this._immediateIndex == null ? index : this._immediateIndex; const currentDragDistance = gesture[isVertical ? 'dy' : 'dx']; const currentDragPosition = event.nativeEvent[isVertical ? 'pageY' : 'pageX']; const axisLength = isVertical ? layout.height.__getValue() : layout.width.__getValue(); const axisHasBeenMeasured = !!axisLength; // Measure the distance from the touch to the edge of the screen const screenEdgeDistance = currentDragPosition - currentDragDistance; // Compare to the gesture distance relavant to card or modal const { gestureResponseDistance: userGestureResponseDistance = {}, } = this._getScreenDetails(scene).options; const gestureResponseDistance = isVertical ? userGestureResponseDistance.vertical || GESTURE_RESPONSE_DISTANCE_VERTICAL : userGestureResponseDistance.horizontal || GESTURE_RESPONSE_DISTANCE_HORIZONTAL; // GESTURE_RESPONSE_DISTANCE is about 25 or 30. Or 135 for modals if (screenEdgeDistance > gestureResponseDistance) { // Reject touches that started in the middle of the screen return false; } const hasDraggedEnough = Math.abs(currentDragDistance) > RESPOND_THRESHOLD; const isOnFirstCard = immediateIndex === 0; const shouldSetResponder = hasDraggedEnough && axisHasBeenMeasured && !isOnFirstCard; return shouldSetResponder; }, onPanResponderMove: (event: any, gesture: any) => { // Handle the moving touches for our granted responder const startValue = this._gestureStartValue; const axis = isVertical ? 'dy' : 'dx'; const axisDistance = isVertical ? layout.height.__getValue() : layout.width.__getValue(); const currentValue = I18nManager.isRTL && axis === 'dx' ? startValue + gesture[axis] / axisDistance : startValue - gesture[axis] / axisDistance; const value = clamp(index - 1, currentValue, index); position.setValue(value); }, onPanResponderTerminationRequest: () => // Returning false will prevent other views from becoming responder while // the navigation view is the responder (mid-gesture) false, onPanResponderRelease: (event: any, gesture: any) => { if (!this._isResponding) { return; } this._isResponding = false; const immediateIndex = this._immediateIndex == null ? index : this._immediateIndex; // Calculate animate duration according to gesture speed and moved distance const axisDistance = isVertical ? layout.height.__getValue() : layout.width.__getValue(); const movedDistance = gesture[isVertical ? 'dy' : 'dx']; const gestureVelocity = gesture[isVertical ? 'vy' : 'vx']; const defaultVelocity = axisDistance / ANIMATION_DURATION; const velocity = Math.max(Math.abs(gestureVelocity), defaultVelocity); const resetDuration = movedDistance / velocity; const goBackDuration = (axisDistance - movedDistance) / velocity; // To asyncronously get the current animated value, we need to run stopAnimation: position.stopAnimation((value: number) => { // If the speed of the gesture release is significant, use that as the indication // of intent if (gestureVelocity < -0.5) { this._reset(immediateIndex, resetDuration); return; } if (gestureVelocity > 0.5) { this._goBack(immediateIndex, goBackDuration); return; } // Then filter based on the distance the screen was moved. Over a third of the way swiped, // and the back will happen. if (value <= index - POSITION_THRESHOLD) { this._goBack(immediateIndex, goBackDuration); } else { this._reset(immediateIndex, resetDuration); } }); }, }); const { options } = this._getScreenDetails(scene); const gesturesEnabled = typeof options.gesturesEnabled === 'boolean' ? options.gesturesEnabled : Platform.OS === 'ios'; const handlers = gesturesEnabled ? responder.panHandlers : {}; const containerStyle = [ styles.container, this._getTransitionConfig().containerStyle, ]; return ( <View {...handlers} style={containerStyle}> <View style={styles.scenes}> {scenes.map((s: *) => this._renderCard(s))} </View> {floatingHeader} </View> ); } _getHeaderMode(): HeaderMode { if (this.props.headerMode) { return this.props.headerMode; } if (Platform.OS === 'android' || this.props.mode === 'modal') { return 'screen'; } return 'float'; } _renderInnerScene( SceneComponent: ReactClass<*>, scene: NavigationScene ): React.Element<any> { const { navigation } = this._getScreenDetails(scene); const { screenProps } = this.props; const headerMode = this._getHeaderMode(); if (headerMode === 'screen') { return ( <View style={styles.container}> <View style={{ flex: 1 }}> <SceneView screenProps={screenProps} navigation={navigation} component={SceneComponent} /> </View> {this._renderHeader(scene, headerMode)} </View> ); } return ( <SceneView screenProps={this.props.screenProps} navigation={navigation} component={SceneComponent} /> ); } _getTransitionConfig = () => { const isModal = this.props.mode === 'modal'; /* $FlowFixMe */ return TransitionConfigs.getTransitionConfig( this.props.transitionConfig, {}, {}, isModal ); }; _renderCard = (scene: NavigationScene): React.Element<*> => { const { screenInterpolator } = this._getTransitionConfig(); const style = screenInterpolator && screenInterpolator({ ...this.props, scene }); const SceneComponent = this.props.router.getComponentForRouteName( scene.route.routeName ); return ( <Card {...this.props} key={`card_${scene.key}`} style={[style, this.props.cardStyle]} scene={scene} > {this._renderInnerScene(SceneComponent, scene)} </Card> ); }; } const styles = StyleSheet.create({ container: { flex: 1, // Header is physically rendered after scenes so that Header won't be // covered by the shadows of the scenes. // That said, we'd have use `flexDirection: 'column-reverse'` to move // Header above the scenes. flexDirection: 'column-reverse', }, scenes: { flex: 1, }, }); export default CardStack;
app/client/components/map/Story.js
breakfast-mimes/cyber-mimes
import React from 'react'; export default class Story extends React.Component { constructor(props) { super(props); this.state = { } } render(){ const { row, col, messages} = this.props; return( <div className='noSelect'> {messages[row] ? messages[row][col] : "No Messages"} </div> ) } }
src/client/components/common/component.header.js
thamht4190/elearning
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import MultilangStrings from '../../languages'; class Header extends Component { render() { return ( <div className="page-header"> <div className="logo page-header-item"> <a href="/"><img src="/img/logo.png" /></a> </div> <div className="page-menu"> <ul> <li><Link to="/wiki">Wiki</Link></li> <li><Link to="/under-frade-2">Under grade 2</Link></li> <li><Link to="/grage-2-5">Grade 2 - 5</Link></li> </ul> </div> </div> ) } } export default Header;
client/ButtonBar.js
npasserini/redux-workshop
import React from 'react'; export default class ButtonBar extends React.Component { render() { let buttons = this.props.buttons.map( (btn, index) => <button key={index} className={btn.className} onClick={(e) => this.props.onButtonClicked(btn.data) }> {btn.label} </button> ); return <div className="buttonBar"> {buttons} </div> } }
vendor/miloschuman/yii2-highcharts-widget/src/assets/highcharts.src.js
tskmatrix/yiicomm
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v4.0.4 (2014-09-02) * * (c) 2009-2014 Torstein Honsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ /*jslint ass: true, sloppy: true, forin: true, plusplus: true, nomen: true, vars: true, regexp: true, newcap: true, browser: true, continue: true, white: true */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isIE = /msie/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext, Renderer, hasTouch, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, error, noop = function () { return UNDEFINED; }, charts = [], chartCount = 0, PRODUCT = 'Highcharts', VERSION = '4.0.4', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', numRegex = /^[0-9]+$/, NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', // Object for extending Axis AxisPlotLineOrBandExtension, // constants for attributes STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used Date, // Allow using a different Date class makeTime, timezoneOffset, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}, Highcharts; // The Highcharts namespace if (win.Highcharts) { error(16, true); } else { Highcharts = win.Highcharts = {}; } /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ function extend(a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; } /** * Deep merge two or more objects and return a third object. If the first argument is * true, the contents of the second object is copied into the first object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, args = arguments, len, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return obj && typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem.setAttribute(prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem.setAttribute(key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ function pick() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (arg !== UNDEFINED && arg !== null) { return arg; } } } /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isIE && !hasSVG) { // #2686 if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () { return UNDEFINED; }; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ function numberFormat(number, decimals, decPoint, thousandsSep) { var externalFn = Highcharts.numberFormat, lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = +number || 0, c = decimals === -1 ? (n.toString().split('.')[1] || '').length : // preserve decimals (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(n).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return externalFn !== numberFormat ? externalFn(number, decimals, decPoint, thousandsSep) : (s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : "")); } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ function wrap(obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp - timezoneOffset), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; if (val !== null) { val = numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, allowDecimals) { var normalized, i; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) { break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ error = function (code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } // else ... if (win.console) { console.log(msg); } }; /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { return parseFloat( num.toPrecision(14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ timeUnits = { millisecond: 1, second: 1000, minute: 60000, hour: 3600000, day: 24 * 3600000, week: 7 * 24 * 3600000, month: 31 * 24 * 3600000, year: 31556952000 }; /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams && start.length === end.length) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) { var obj = Fx.step, base; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && $.Tween) { // jQuery 1.8 model obj = $.Tween.propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { var elem; // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // Don't run animations on textual properties like align (#1821) if (fx.prop === 'align') { return; } // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+ wrap($.cssHooks.opacity, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) this.addAnimSetter('d', function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // Interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }); /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i, len = arr.length; for (i = 0; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Register Highcharts as a plugin in the respective framework */ $.fn.highcharts = function () { var constr = 'Chart', // default constructor args = arguments, options, ret, chart; if (this[0]) { if (isString(args[0])) { constr = args[0]; args = Array.prototype.slice.call(args, 1); } options = args[0]; // Create the chart if (options !== UNDEFINED) { /*jslint unused:false*/ options.chart = options.chart || {}; options.chart.renderTo = this[0]; chart = new Highcharts[constr](options, args[1]); ret = this; /*jslint unused:true*/ } // When called without parameters or with the return argument, get a predefined chart if (options === UNDEFINED) { ret = charts[attr(this[0], 'data-highcharts-chart')]; } } return ret; }; }, /** * Add an animation setter for a specific property */ addAnimSetter: function (prop, setter) { // jQuery 1.8 style if ($.Tween) { $.Tween.propHooks[prop] = { set: setter }; // pre 1.8 } else { $.fx.step[prop] = setter; } }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && el && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isIE && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; delete eventArguments.returnValue; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (!el.style) { el.style = {}; // #1881 } if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); if (params.opacity !== UNDEFINED && el.attr) { params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161) } el.hasAnim = 1; // #3342 $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy $(el).stop(); } } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ var defaultLabelOptions = { enabled: true, // rotation: 0, // align: 'center', x: 0, y: 15, /*formatter: function () { return this.value; },*/ style: { color: '#606060', cursor: 'default', fontSize: '11px' } }; defaultOptions = { colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ',' }, global: { useUTC: true, //timezoneOffset: 0, canvasToolsURL: 'http://code.highcharts.com/4.0.4/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/4.0.4/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 0, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, //style: { // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font // fontSize: '12px' //}, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#333333', fontSize: '18px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#555555' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, //linecap: 'round', lineWidth: 2, //shadow: false, // stacking: null, marker: { //enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true, lineWidthPlus: 1, radiusPlus: 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { align: 'center', //defer: true, enabled: false, formatter: function () { return this.y === null ? '' : numberFormat(this.y, -1); }, verticalAlign: 'bottom', // above singular point y: 0 // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, // padding: 3, // shadow: false }), cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series states: { // states for the entire series hover: { //enabled: false, lineWidthPlus: 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10, opacity: 0.25 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, //borderWidth: 0, borderColor: '#909090', borderRadius: 0, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 20, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { color: '#333333', fontSize: '12px', fontWeight: 'bold' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, // symbolRadius: 0, // symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '45%' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(249, 249, 249, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', shadow: true, //shape: 'callout', //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var useUTC = defaultOptions.global.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; Date = defaultOptions.global.Date || window.Date; timezoneOffset = ((useUTC && defaultOptions.global.timezoneOffset) || 0) * 60000; makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) { return new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Copy in the default options defaultOptions = merge(true, defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/, hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/; var Color = function (input) { // declare variables var rgba = [], result, stops; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // Gradients if (input && input.stops) { stops = map(input.stops, function (stop) { return Color(stop[1]); }); // Solid colors } else { // rgba result = rgbaRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = hexRegEx.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = rgbRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } } } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; if (stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (stops) { each(stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, rgba: rgba, setOpacity: setOpacity }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { // Default base for animation opacity: 1, // For labels, these CSS properties are applied to the <text> node directly textProps: ['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow', 'HcTextStroke'], /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions, {}); //#2625 if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } return this; }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { gradAttr = merge(gradAttr, { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2], gradientUnits: 'userSpaceOnUse' }); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')'); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr; // single key-value pair if (typeof hash === 'string' && val !== UNDEFINED) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element); } // Let the shadow follow the main element if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { this.updateShadows(key, value); } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } return ret; }, updateShadows: function (key, value) { var shadows = this.shadows, i = shadows.length; while (i--) { shadows[i].setAttribute( key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value ); } }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (rect) { var wrapper = this, key, attribs = {}, normalizer, strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer; rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer; rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer); rect.strokeWidth = strokeWidth; for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width); // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { css(elemWrapper.element, styles); } else { /*jslint unparam: true*/ hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { this.element.radialReference = coordinates; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, element = wrapper.element, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function () { var wrapper = this, bBox = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad, textStr = wrapper.textStr, cacheKey; // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. if (textStr === '' || numRegex.test(textStr)) { cacheKey = 'num.' + textStr.toString().length + (styles ? ('|' + styles.fontSize + '|' + styles.fontFamily) : ''); } //else { // This code block made demo/waterfall fail, related to buildText // Caching all strings reduces rendering time by 4-5%. // TODO: Check how this affects places where bBox is found on the element //cacheKey = textStr + (styles ? ('|' + styles.fontSize + '|' + styles.fontFamily) : ''); //} if (cacheKey) { bBox = renderer.cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } // Cache it wrapper.bBox = bBox; if (cacheKey) { renderer.cache[cacheKey] = bBox; } } return bBox; }, /** * Show the element */ show: function (inherit) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881) if (inherit && this.element.namespaceURI === SVG_NS) { this.element.removeAttribute('visibility'); } else { this.attr({ visibility: inherit ? 'inherit' : VISIBLE }); } return this; }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, element = this.element, zIndex = this.zIndex, otherElement, otherZIndex, i, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // mark the container as having z indexed children if (zIndex) { parentWrapper.handleZ = true; zIndex = pInt(zIndex); } // insert according to this and other elements' zIndex if (parentWrapper.handleZ) { // this element or any of its siblings has a z index childNodes = parentNode.childNodes; for (i = 0; i < childNodes.length; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // insert before the first element with a higher zIndex pInt(otherZIndex) > zIndex || // if no zIndex given, insert before the first element with a zIndex (!defined(zIndex) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; break; } } } // default: append at the end if (!inserted) { parentNode.appendChild(element); } // mark as added this.added = true; // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697). while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; }, xGetter: function (key) { if (this.element.nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function (key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, dashstyleSetter: function (value) { var i; value = value && value.toLowerCase(); if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * this['stroke-width']; } value = value.join(',') .replace('NaN', 'none'); // #3226 this.element.setAttribute('stroke-dasharray', value); } }, alignSetter: function (value) { this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]); }, opacitySetter: function (value, key, element) { this[key] = value; element.setAttribute(key, value); }, titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); this.element.appendChild(titleNode); } titleNode.textContent = pick(value, '').replace(/<[^>]*>/g, ''); // #3276 }, textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, zIndexSetter: function (value, key, element) { element.setAttribute(key, value); this[key] = value; }, _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) { this[key] = value; this.doTransform = true; }; // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the // stroke attribute altogether. #1270, #1369, #3065, #3072. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (this.stroke && this['stroke-width']) { this.strokeWidth = this['stroke-width']; SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { element.removeAttribute('stroke'); this.hasStroke = false; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, style, forExport) { var renderer = this, loc = location, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }) .css(this.getStyle(style)); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, getStyle: function (style) { return (this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, style)); }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, styleRegex, hrefRegex, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textStroke = textStyles && textStyles.HcTextStroke, i = childNodes.length, getLineHeight = function (tspan) { return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12), tspan ).h; }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if (!hasMarkup && !textStroke && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(textStr)); return; // Complex strings, add more logic } else { styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = (span.replace(/<(.|\n)*?>/g, '') || ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>'); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan) ); } // check width and apply soft breaks if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 hasWhiteSpace = spans.length > 1 || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'), tooLong, actualWidth, hcHeight = textStyles.HcHeight, rest = [], dy = getLineHeight(tspan), softLineNo = 1, bBox; while (hasWhiteSpace && (words.length || rest.length)) { delete wrapper.bBox; // delete cache bBox = wrapper.getBBox(); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!hasSVG && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; if (!tooLong || words.length === 1) { // new line needed words = rest; rest = []; if (words.length) { softLineNo++; if (hcHeight && softLineNo * dy > hcHeight) { words = ['...']; wrapper.attr('title', wrapper.textStr); } else { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); } } if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } } spanNo++; } } }); }); } }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState.style; delete normalState.style; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState.style; delete hoverState.style; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState.style; delete pressedState.style; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState.style; delete disabledState.style; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function () { if (curState !== 3) { callback.call(label); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }, wrapper = this.createElement('circle'); wrapper.xSetter = function (value) { this.element.setAttribute('cx', value); }; wrapper.ySetter = function (value) { this.element.setAttribute('cy', value); }; return wrapper.attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === UNDEFINED ? {} : { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; if (strokeWidth !== UNDEFINED) { attribs.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } if (r) { attribs.r = r; } wrapper.rSetter = function (value) { attr(this.element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]); // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = mathMin((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors; x += normalizer; y += normalizer; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; return wrapper; }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper, attr = {}; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } attr.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attr.y = Math.round(y); } if (str || str === 0) { attr.text = str; } wrapper = renderer.createElement('text') .attr(attr); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } if (!useHTML) { wrapper.xSetter = function (value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize, elem) { fontSize = fontSize || this.style.fontSize; if (elem && win.getComputedStyle) { elem = elem.element || elem; // SVGElement fontSize = win.getComputedStyle(elem, "").fontSize; } fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline, f: fontSize }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && text.textStr && text.getBBox(); wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding); boxY = baseline ? -baselineOffset : 0; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.attr('fill', NONE).add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(extend({ width: mathRound(wrapper.width), height: mathRound(wrapper.height) }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr('x', x); if (y !== UNDEFINED) { text.attr('y', y); } } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = value; }; wrapper.heightSetter = function (value) { height = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== UNDEFINED) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } crispAdjust = value % 2 / 2; boxAttr(key, value); }; wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key === 'fill' && value) { needsBox = true; } boxAttr(key, value); }; wrapper.anchorXSetter = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + padding); } wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(wrapper.textProps, function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element, bBox = wrapper.bBox; // faking getBBox in exported SVG in legacy IE if (!bBox) { // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } bBox = wrapper.bBox = { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; } return bBox; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], shadows = wrapper.shadows; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } width = pick(wrapper.elemWidth, elem.offsetWidth); // Update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + PX, top: (y + (wrapper.yCorr || 0)) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function (width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer; // Text setter wrapper.textSetter = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; }; // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, whiteSpace: 'nowrap', fontFamily: this.style.fontFamily, fontSize: this.style.fontSize }); // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle; // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, { className: attr(parentGroup.element, 'class') }, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup, { translateXSetter: function (value, key) { htmlGroupStyle.left = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function (value, key) { htmlGroupStyle.top = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, visibilitySetter: function (value, key) { htmlGroupStyle[key] = value; } }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; } }); /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks if (wrapper.onAdd) { wrapper.onAdd(); } return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function () { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = mathCos(rotation * deg2rad), sintheta = mathSin(rotation * deg2rad); css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Get the positioning correction for the span after rotating. */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? mathCos(rotation * deg2rad) : 1, sintheta = rotation ? mathSin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = costheta < 0 && -width; this.yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(this.element, { textAlign: align }); } }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract or // add 1 from the end X and Y positions. #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; }, updateShadows: noop, // Used in SVG only setAttr: function (key, value) { if (docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless set like this this.element.className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this[key] = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; this.d = value.join && value.join(' '); // used in getter for animation element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts rotationSetter: function (value, key, element) { var style = element.style; this[key] = style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; style.top = mathRound(mathCos(value * deg2rad)) + PX; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = VISIBLE; } // Let the shadow follow the main element if (this.shadows) { each(this.shadows, function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (element.nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { element.style[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; }/* else { value = mathMax(0, value); // don't set width or height below zero (#311) }*/ // clipping rectangle special if (this.updateClipping) { this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; } }; Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height, style) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV) .css(extend(this.getStyle(style), { position: RELATIVE})); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.cache = {}; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do. member.css(clipRect.getCSS(member)); } }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right wrapper.onAdd = applyRadialGradient; } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1), top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1), rotation: -90 }); // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806. each(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape. When borders are not rounded, * use the simpler square path, else use the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[ !defined(options) || !options.r ? 'square' : 'callout' ].call(0, x, y, w, h, options); } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return offsetWidth; }; /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, horiz = axis.horiz, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, rotation = labelOptions.rotation, str, tickPositions = axis.tickPositions, width = (horiz && categories && !labelOptions.step && !labelOptions.staggerLines && !labelOptions.rotation && chart.plotWidth / tickPositions.length) || (!horiz && (chart.margin[3] || chart.chartWidth * 0.33)), // #1580, #1931 isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], css, attr, value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; // first call if (!defined(label)) { attr = { align: axis.labelAlign }; if (isNumber(rotation)) { attr.rotation = rotation; } if (width && labelOptions.ellipsis) { css.HcHeight = axis.len / tickPositions.length; } tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .attr(attr) // without position absolute, IE export sometimes is wrong .css(extend(css, labelOptions.style)) .add(axis.labelGroup) : null; // Set the tick baseline and correct for rotation (#1764) axis.tickBaseline = chart.renderer.fontMetrics(labelOptions.style.fontSize, label).b; if (rotation && axis.side === 2) { axis.tickBaseline *= mathCos(rotation * deg2rad); } // update } else if (label) { label.attr({ text: str }) .css(css); } tick.yOffset = label ? pick(labelOptions.y, axis.tickBaseline + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))) : 0; }, /** * Get the offset height or width of the label */ getLabelSize: function () { var label = this.label, axis = this.axis; return label ? label.getBBox()[axis.horiz ? 'height' : 'width'] : 0; }, /** * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision * detection with overflow logic. */ getLabelSides: function () { var bBox = this.label.getBBox(), axis = this.axis, horiz = axis.horiz, options = axis.options, labelOptions = options.labels, size = horiz ? bBox.width : bBox.height, leftSide = horiz ? labelOptions.x - size * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] : 0, rightSide = horiz ? size + leftSide : size; return [leftSide, rightSide]; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (index, xy) { var show = true, axis = this.axis, isFirst = this.isFirst, isLast = this.isLast, horiz = axis.horiz, pxPos = horiz ? xy.x : xy.y, reversed = axis.reversed, tickPositions = axis.tickPositions, sides = this.getLabelSides(), leftSide = sides[0], rightSide = sides[1], axisLeft, axisRight, neighbour, neighbourEdge, line = this.label.line, lineIndex = line || 0, labelEdge = axis.labelEdge, justifyLabel = axis.justifyLabels && (isFirst || isLast), justifyToPlot; // Hide it if it now overlaps the neighbour label if (labelEdge[lineIndex] === UNDEFINED || pxPos + leftSide > labelEdge[lineIndex]) { labelEdge[lineIndex] = pxPos + rightSide; } else if (!justifyLabel) { show = false; } if (justifyLabel) { justifyToPlot = axis.justifyToPlot; axisLeft = justifyToPlot ? axis.pos : 0; axisRight = justifyToPlot ? axisLeft + axis.len : axis.chart.chartWidth; // Find the firsth neighbour on the same line do { index += (isFirst ? 1 : -1); neighbour = axis.ticks[tickPositions[index]]; } while (tickPositions[index] && (!neighbour || !neighbour.label || neighbour.label.line !== line)); // #3044 neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1]; if ((isFirst && !reversed) || (isLast && reversed)) { // Is the label spilling out to the left of the plot area? if (pxPos + leftSide < axisLeft) { // Align it to plot left pxPos = axisLeft - leftSide; // Hide it if it now overlaps the neighbour label if (neighbour && pxPos + rightSide > neighbourEdge) { show = false; } } } else { // Is the label spilling out to the right of the plot area? if (pxPos + rightSide > axisRight) { // Align it to plot right pxPos = axisRight - rightSide; // Hide it if it now overlaps the neighbour label if (neighbour && pxPos + leftSide < neighbourEdge) { show = false; } } } // Set the modified x position of the label xy.x = pxPos; } return show; }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines; x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + this.yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { label.line = (index / (step || 1) % staggerLines); y += label.line * (axis.labelOffset / staggerLines); } return { x: x, y: y }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = options[tickPrefix + 'Width'] || 0, tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 opacity = pick(opacity, 1); this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (!axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { show = tick.handleOverflow(index, xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ Highcharts.PlotLineOrBand = function (axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } }; Highcharts.PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, halfPointRange = (axis.pointRange || 0) / 2, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs = {}, renderer = axis.chart.renderer; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band // keep within plot area from = mathMax(from, axis.min - halfPointRange); to = mathMin(to, axis.max + halfPointRange); path = axis.getPlotBandPath(from, to, options); if (color) { attribs.fill = color; } if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function () { svgElem.show(); }; if (label) { plotLine.label = label = label.destroy(); } } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign : !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); // add the SVG element if (!label) { attribs = { align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation }; if (defined(zIndex)) { attribs.zIndex = zIndex; } plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr(attribs) .css(optionsLabel.style) .add(); } // get the bounding box and align the label // #3000 changed to better handle choice between plotband or plotline xs = [path[1], path[4], (isBand ? path[6] : path[1])]; ys = [path[2], path[5], (isBand ? path[7] : path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function () { // remove it from the lookup erase(this.axis.plotLinesAndBands, this); delete this.axis; destroyObjectProperties(this); } }; /** * Object with members for extending the Axis prototype */ AxisPlotLineOrBandExtension = { /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to), path = this.getPlotLinePath(from); if (path && toPath) { path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, addPlotBand: function (options) { return this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { return this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options, coll) { var obj = new Highcharts.PlotLineOrBand(this, options).render(), userOptions = this.userOptions; if (obj) { // #2189 // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); } return obj; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, options = this.options, userOptions = this.userOptions, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) { i = arr.length; while (i--) { if (arr[i].id === id) { erase(arr, arr[i]); } } }); } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ function Axis() { this.init.apply(this, arguments); } Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#C0C0C0', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: defaultLabelOptions, // { step: null }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 10, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#707070' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return numberFormat(this.total, -1); }, style: defaultLabelOptions.style } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -15, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { x: 0, y: null // based on font size // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for left axes */ defaultTopAxisOptions: { labels: { x: 0, y: -15 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.coll = isXAxis ? 'xAxis' : 'yAxis'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.side || (axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3)); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series //axis.ignoreMaxPadding = UNDEFINED; axis.chart = chart; axis.reversed = options.reversed; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; axis.names = []; // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between' && pick(options.tickInterval, 1) === 1) ? 0.5 : 0; // #3202 // Major ticks axis.ticks = {}; axis.labelEdge = []; // Minor ticks axis.minorTicks = {}; //axis.tickAmount = UNDEFINED; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis && !this.isColorAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && numericSymbols[i] !== null) { ret = numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (mathAbs(value) >= 10000) { // add thousands separators ret = numberFormat(value, 0); } else { // small numbers ret = numberFormat(value, -1, UNDEFINED, ''); // #2466 } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // Reset properties in case we're redrawing (#3353) axis.dataMin = axis.dataMax = axis.ignoreMinPadding = axis.ignoreMaxPadding = null; if (axis.buildStacks) { axis.buildStacks(); } // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this, sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (postTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (postTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; if (x1 < axisLeft || x1 > axisLeft + axis.width) { skip = true; } } else { x1 = axisLeft; x2 = cWidth - axis.right; if (y1 < axisTop || y1 > axisTop + axis.height) { skip = true; } } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1); }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, len; if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( axis.getTimeTicks( axis.normalizeTimeTickInterval(minorTickInterval), axis.min, axis.max, options.startOfWeek ) ); if (minorTickPositions[0] < axis.min) { minorTickPositions.shift(); } } else { for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) { minorTickPositions.push(pos); } } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { var minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (axis.isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = hasCategories ? 1 : (axis.isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806 pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; if (seriesPointRange > range) { // #1446 seriesPointRange = 0; } pointRange = mathMax(pointRange, seriesPointRange); // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value axis.closestPointRange = closestPointRange; } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickPositions: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, startOnTick = options.startOnTick, endOnTick = options.endOnTick, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, tickPositioner = axis.options.tickPositioner, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickIntervalOption = options.minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, tickPositions, keepTwoTicksOnly, categories = axis.categories; // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[axis.coll][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } } else { // initial min and max from the extreme data values axis.min = pick(axis.userMin, options.min, axis.dataMin); axis.max = pick(axis.userMax, options.max, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934 axis.max = correctFloat(log2lin(axis.max)); } // handle zoomed range if (axis.range && defined(axis.max)) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; axis.range = null; // don't use it when running setExtremes } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) { axis.min -= length * minPadding; } if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) { axis.max += length * maxPadding; } } } // Stay within floor and ceiling if (isNumber(options.floor)) { axis.min = mathMax(axis.min, options.floor); } if (isNumber(options.ceiling)) { axis.max = mathMin(axis.max, options.ceiling); } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); // For squished axes, set only two ticks if (!defined(tickIntervalOption) && axis.len < tickPixelIntervalOption && !this.isRadial && !this.isLog && !categories && startOnTick && endOnTick) { keepTwoTicksOnly = true; axis.tickInterval /= 4; // tick extremes closer to the real values } } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943) if (axis.pointRange) { axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) { axis.tickInterval = minTickIntervalOption; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog) { // linear if (!tickIntervalOption) { axis.tickInterval = normalizeTickInterval( axis.tickInterval, null, getMagnitude(axis.tickInterval), // If the tick interval is between 1 and 5 and the axis max is in the order of // thousands, chances are we are dealing with years. Don't allow decimals. #3363. pick(options.allowDecimals, !(axis.tickInterval > 1 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)) ); } } // get minorTickInterval axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ? axis.tickInterval / 5 : options.minorTickInterval; // find the tick positions axis.tickPositions = tickPositions = options.tickPositions ? [].concat(options.tickPositions) : // Work on a copy (#1565) (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max])); if (!tickPositions) { // Too many ticks if (!axis.ordinalPositions && (axis.max - axis.min) / axis.tickInterval > mathMax(2 * axis.len, 200)) { error(19, true); } if (isDatetimeAxis) { tickPositions = axis.getTimeTicks( axis.normalizeTimeTickInterval(axis.tickInterval, options.units), axis.min, axis.max, options.startOfWeek, axis.ordinalPositions, axis.closestPointRange, true ); } else if (isLog) { tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max); } else { tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max); } if (keepTwoTicksOnly) { tickPositions.splice(1, tickPositions.length - 2); } axis.tickPositions = tickPositions; } if (!isLinked) { // reset min/max or remove extremes based on start/end on tick var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = axis.minPointOffset || 0, singlePad; if (startOnTick) { axis.min = roundedMin; } else if (axis.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (endOnTick) { axis.max = roundedMax; } else if (axis.max + minPointOffset < roundedMax) { tickPositions.pop(); } // If no tick are left, set one tick in the middle (#3195) if (tickPositions.length === 0 && defined(roundedMin)) { tickPositions.push((roundedMax + roundedMin) / 2); } // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (tickPositions.length === 1) { singlePad = mathAbs(axis.max) > 10e12 ? 1 : 0.001; // The lowest possible number to avoid extra padding on columns (#2619, #2846) axis.min -= singlePad; axis.max += singlePad; } } }, /** * Set the max ticks of either the x and y axis collection */ setMaxTicks: function () { var chart = this.chart, maxTicks = chart.maxTicks || {}, tickPositions = this.tickPositions, key = this._maxTicksKey = [this.coll, this.pos, this.len].join('-'); if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) { maxTicks[key] = tickPositions.length; } chart.maxTicks = maxTicks; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var axis = this, chart = axis.chart, key = axis._maxTicksKey, tickPositions = axis.tickPositions, maxTicks = chart.maxTicks; if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false && this.min !== UNDEFINED) { var oldTickAmount = axis.tickAmount, calculatedTickAmount = tickPositions.length, tickAmount; // set the axis-level tickAmount to use below axis.tickAmount = tickAmount = maxTicks[key]; if (calculatedTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + axis.tickInterval )); } axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1); axis.max = tickPositions[tickPositions.length - 1]; } if (defined(oldTickAmount) && tickAmount !== oldTickAmount) { axis.isDirty = true; } } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, stacks = axis.stacks, type, i, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { // reset stacks if (!axis.isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].total = null; stacks[type][i].cum = 0; } } } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickPositions(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (!axis.isXAxis) { if (axis.oldStacks) { stacks = axis.stacks = axis.oldStacks; } // reset stacks for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } // Set the maximum tick amount axis.setMaxTicks(); }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; // Mark for running afterSetExtremes axis.isDirtyExtremes = true; // redraw if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options; // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= mathMin(dataMin, pick(options.min, dataMin))) { newMin = UNDEFINED; } if (defined(dataMax) && newMax >= mathMax(dataMax, pick(options.max, dataMax))) { newMax = UNDEFINED; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // Check for percentage based input values if (percentRegex.test(height)) { height = parseInt(height, 10) / 100 * chart.plotHeight; } if (percentRegex.test(top)) { top = parseInt(top, 10) / 100 * chart.plotHeight + chart.plotTop; } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog; var realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (realMin > threshold || threshold === null) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset labelOffsetPadded, axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, directionFactor = [-1, 1, 1, -1][side], n, i, autoStaggerLines = 1, maxStaggerLines = pick(labelOptions.maxStaggerLines, 5), sortedPositions, lastRight, overlap, pos, bBox, x, w, lineNo, lineHeightCorrection; // For reuse in Axis.render axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions)); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .addClass(PREFIX + axis.coll.toLowerCase() + '-labels') .add(); } if (hasData || axis.isLinked) { // Set the explicit or automatic label alignment axis.labelAlign = pick(labelOptions.align || axis.autoLabelAlign(labelOptions.rotation)); // Generate ticks each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); // Handle automatic stagger lines if (axis.horiz && !axis.staggerLines && maxStaggerLines && !labelOptions.rotation) { sortedPositions = axis.reversed ? [].concat(tickPositions).reverse() : tickPositions; while (autoStaggerLines < maxStaggerLines) { lastRight = []; overlap = false; for (i = 0; i < sortedPositions.length; i++) { pos = sortedPositions[i]; bBox = ticks[pos].label && ticks[pos].label.getBBox(); w = bBox ? bBox.width : 0; lineNo = i % autoStaggerLines; if (w) { x = axis.translate(pos); // don't handle log if (lastRight[lineNo] !== UNDEFINED && x < lastRight[lineNo]) { overlap = true; } lastRight[lineNo] = x + w; } } if (overlap) { autoStaggerLines++; } else { break; } } if (autoStaggerLines > 1) { axis.staggerLines = autoStaggerLines; } } each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .addClass(PREFIX + this.coll.toLowerCase() + '-title') .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleOffsetOption = axisTitleOptions.offset; titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10); } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); lineHeightCorrection = side === 2 ? axis.tickBaseline : 0; labelOffsetPadded = labelOffset + titleMargin + (labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickBaseline + 8) : labelOptions.x) - lineHeightCorrection)); axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset, labelOffsetPadded // #3027 ); clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis : offAxis + (opposite ? this.width : 0) + offset + (axisTitleOptions.x || 0), // x y: horiz ? offAxis - (opposite ? this.height : 0) + offset : alongAxis + (axisTitleOptions.y || 0) // y }; }, /** * Render the axis */ render: function () { var axis = this, horiz = axis.horiz, reversed = axis.reversed, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, sortedPositions, axisTitle = axis.axisTitle, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), hasData = axis.hasData, showAxis = axis.showAxis, from, overflow = options.labels.overflow, justifyLabels = axis.justifyLabels = horiz && overflow !== false, to; // Reset axis.labelEdge.length = 0; axis.justifyToPlot = overflow === 'justify'; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 sortedPositions = tickPositions.slice(); if ((horiz && reversed) || (!horiz && !reversed)) { sortedPositions.reverse(); } if (justifyLabels) { sortedPositions = sortedPositions.slice(1).concat([sortedPositions[0]]); } each(sortedPositions, function (pos, i) { // Reorganize the indices if (justifyLabels) { i = (i === sortedPositions.length - 1) ? 0 : i + 1; } // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true, 0.1); } ticks[pos].render(i); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && axis.min === 0) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { if (i % 2 === 0 && pos < axis.max) { if (!alternateBands[pos]) { alternateBands[pos] = new Highcharts.PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max; alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them if (coll === alternateBands || !chart.hasRendered || !delay) { destroyInactiveItems(); } else if (delay) { setTimeout(destroyInactiveItems, delay); } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { // render the axis this.render(); // move plot lines and bands each(this.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(this.series, function (series) { series.isDirty = true; }); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); // Destroy crosshair if (this.cross) { this.cross.destroy(); } }, /** * Draw the crosshair */ drawCrosshair: function (e, point) { if (!this.crosshair) { return; }// Do not draw crosshairs if you don't have too. if ((defined(point) || !pick(this.crosshair.snap, true)) === false) { this.hideCrosshair(); return; } var path, options = this.crosshair, animation = options.animation, pos; // Get the path if (!pick(options.snap, true)) { pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { /*jslint eqeq: true*/ pos = (this.chart.inverted != this.horiz) ? point.plotX : this.len - point.plotY; /*jslint eqeq: false*/ } if (this.isRadial) { path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)); } else { path = this.getPlotLinePath(null, null, null, null, pos); } if (path === null) { this.hideCrosshair(); return; } // Draw the cross if (this.cross) { this.cross .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation); } else { var attribs = { 'stroke-width': options.width || 1, stroke: options.color || '#C0C0C0', zIndex: options.zIndex || 2 }; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } this.cross = this.chart.renderer.path(path).attr(attribs).add(); } }, /** * Hide the crosshair. */ hideCrosshair: function () { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(Axis.prototype, AxisPlotLineOrBandExtension); /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min - timezoneOffset), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 if (interval >= timeUnits.second) { // second minDate.setMilliseconds(0); minDate.setSeconds(interval >= timeUnits.minute ? 0 : count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits.minute) { // minute minDate[setMinutes](interval >= timeUnits.hour ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits.hour) { // hour minDate[setHours](interval >= timeUnits.day ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits.day) { // day minDate[setDate](interval >= timeUnits.month ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits.month) { // month minDate[setMonth](interval >= timeUnits.year ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits.year) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits.week) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; if (timezoneOffset) { minDate = new Date(minDate.getTime() + timezoneOffset); } minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), localTimezoneOffset = (timeUnits.day + (useUTC ? timezoneOffset : minDate.getTimezoneOffset() * 60 * 1000) ) % timeUnits.day; // #950, #3359 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits.year) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits.month) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval === timeUnits.day || interval === timeUnits.week)) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits.day ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * count; } i++; } // push the last time tickPositions.push(time); // mark new days if the time is dividible by day (#1649, #1760) each(grep(tickPositions, function (time) { return interval <= timeUnits.hour && time % timeUnits.day === localTimezoneOffset; }), function (time) { higherRanks[time] = 'day'; }); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; }; /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) { var units = unitsOption || [[ 'millisecond', // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ 'second', [1, 2, 5, 10, 15, 30] ], [ 'minute', [1, 2, 5, 10, 15, 30] ], [ 'hour', [1, 2, 3, 4, 6, 8, 12] ], [ 'day', [1, 2] ], [ 'week', [1, 2] ], [ 'month', [1, 2, 3, 4, 6] ], [ 'year', null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits.year && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval( tickInterval / interval, multiples, unit[0] === 'year' ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360 ); return { unitRange: interval, count: count, unitName: unit[0] }; };/** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.getLogTickPositions = function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; };/** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ var Tooltip = Highcharts.Tooltip = function () { this.init.apply(this, arguments); }; Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add() .attr({ y: -9999 }); // #2301, #2657 // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden && // When we get close to the target position, abort animation and land on the right place (#3056) (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // Move to the intermediate value tooltip.label.attr(now); // Run on next tick of the mouse tracker if (animate) { // Never allow two timeouts clearTimeout(this.tooltipTimeout); // Set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function (delay) { var tooltip = this, hoverPoints; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) if (!this.isHidden) { hoverPoints = this.chart.hoverPoints; this.hideTimer = setTimeout(function () { tooltip.label.fadeOut(); tooltip.isHidden = true; }, pick(delay, this.options.hideDelay, 500)); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotX = 0, plotY = 0, yAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; plotX += point.plotX; plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft], // The far side is right or bottom preferFarSide = point.ttBelow || (chart.inverted && !point.negative) || (!chart.inverted && point.negative), /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function (dim, outerSize, innerSize, point) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = alignedLeft; } else if (roomRight) { ret[dim] = alignedRight; } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function (dim, outerSize, innerSize, point) { // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { return false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } }, /** * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), series = items[0].series, s; // build the header s = [tooltip.tooltipHeaderFormatter(items[0])]; // build the values each(items, function (item) { series = item.series; s.push((series.tooltipFormatter && series.tooltipFormatter(item)) || item.point.tooltipFormatter(series.tooltipOptions.pointFormat)); }); // footer s.push(tooltip.options.footerFormat || ''); return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow }); this.isHidden = false; } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y), point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); }, /** * Format the header of the tooltip */ tooltipHeaderFormatter: function (point) { var series = point.series, tooltipOptions = series.tooltipOptions, dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key), headerFormat = tooltipOptions.headerFormat, closestPointRange = xAxis && xAxis.closestPointRange, n; // Guess the best date format based on the closest point distance (#568) if (isDateTime && !xDateFormat) { if (closestPointRange) { for (n in timeUnits) { if (timeUnits[n] >= closestPointRange || // If the point is placed every day at 23:59, we need to show // the minutes as well. This logic only works for time units less than // a day, since all higher time units are dividable by those. #2637. (timeUnits[n] <= timeUnits.day && point.key % timeUnits[n] > 0)) { xDateFormat = dateTimeLabelFormats[n]; break; } } } else { xDateFormat = dateTimeLabelFormats.day; } xDateFormat = xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 } // Insert the header date format if any if (isDateTime && xDateFormat) { headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(headerFormat, { point: point, series: series }); } }; var hoverChartIndex; // Global flag for touch support hasTouch = doc.documentElement.ontouchstart !== UNDEFINED; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ var Pointer = Highcharts.Pointer = function (chart, options) { this.init(chart, options); }; Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.hasZoom = zoomX || zoomY; // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (Highcharts.Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = options.tooltip.followTouchMove; } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // common IE normalizing e = e || window.event; // Framework specific normalizing (#1165) e = washMouseEvent(e); // More IE normalizing, needs to go after washMouseEvent if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * Return the index in the tooltipPoints array, corresponding to pixel position in * the plot area. */ getIndex: function (e) { var chart = this.chart; return chart.inverted ? chart.plotHeight + chart.plotTop - e.chartY : e.chartX - chart.plotLeft; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, followPointer, point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chart.chartWidth, index = pointer.getIndex(e), anchor; // shared tooltip if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].options.enableMouseTracking !== false && !series[j].noSharedTooltip && series[j].singularTooltips !== true && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; if (point && point.series) { // not a dummy point, #1544 point._dist = mathAbs(index - point.clientX); distance = mathMin(distance, point._dist); points.push(point); } } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].clientX !== pointer.hoverX)) { tooltip.refresh(points, e); pointer.hoverX = points[0].clientX; } } // Separate tooltip and general mouse events followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (hoverSeries && hoverSeries.tracker && !followPointer) { // #2584, #2830 // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point !== hoverPoint) { // trigger the events point.onMouseOver(e); } } else if (tooltip && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } // Start the event listener to pick up the tooltip if (tooltip && !pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.onDocumentMouseMove(e); } }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Draw independent crosshairs each(chart.axes, function (axis) { axis.drawCrosshair(e, pick(point, hoverPoint)); }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove, delay) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(delay); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); pointer.hoverX = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY, panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key']; // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) { if (!this.selectionMarker) { this.selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (this.selectionMarker && zoomHor) { size = chartX - mouseDownX; this.selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (this.selectionMarker && zoomVert) { size = chartY - mouseDownY; this.selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !this.selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled) { var horiz = axis.horiz, minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075 selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[axis.coll].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes, max: mathMax(selectionMin, selectionMax) }); runZoom = true; } } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition, hoverSeries = chart.hoverSeries; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { var chart = charts[hoverChartIndex]; if (chart) { chart.pointer.reset(); chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix } }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; hoverChartIndex = chart.index; e = this.normalize(e); e.returnValue = false; // #2251, #3224 if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement, relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499 if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') && relatedSeries !== series) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; e = this.normalize(e); e.cancelBubble = true; // IE specific if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container; container.onmousedown = function (e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function (e) { pointer.onContainerMouseMove(e); }; container.onclick = function (e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (hasTouch) { container.ontouchstart = function (e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function (e) { pointer.onContainerTouchMove(e); }; if (chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; /* Support for touch devices */ extend(Highcharts.Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, followTouchMove = self.followTouchMove, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || self.runChartClick), clip = {}; // On touch devices, only proceed to trigger click if a handler is defined if ((hasZoom || followTouchMove) && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(pick(axis.options.min, axis.dataMin)), max = axis.toPixels(pick(axis.options.max, axis.dataMax)), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); self.res = true; // reset on next move // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop }, chart.plotBox); } self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } else if (self.res) { self.res = false; this.reset(false, 0); } } }, onContainerTouchStart: function (e) { var chart = this.chart; hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { // Run mouse events and display tooltip etc this.runPointActions(e); this.pinch(e); } else { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchMove: function (e) { if (e.touches.length === 1 || e.touches.length === 2) { this.pinch(e); } }, onDocumentTouchEnd: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } } }); if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function () { var key, fake = []; fake.item = function (i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function (e, method, wktype, callback) { var p; e = e.originalEvent || e; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) { callback(e); p = charts[hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function (e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function (e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function (e) { translateMSPointer(e, 'onContainerTouchEnd', 'touchend', function (e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function (fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom || this.followTouchMove) { css(chart.container, { '-ms-touch-action': NONE, 'touch-action': NONE }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function (proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function (proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } /** * The overview of the chart's series */ var Legend = Highcharts.Legend = function (chart, options) { this.init(chart, options); }; Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding = pick(options.padding, 8), itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding; legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.lastLineHeight = 0; legend.symbolWidth = pick(options.symbolWidth, 16); legend.pages = []; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 symbolAttr.stroke = symbolColor; markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox; if (item.legendGroup) { item.legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item), ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline || 0, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for all if (!legend.baseline) { legend.baseline = renderer.fontMetrics(itemStyle.fontSize, li).f + 3 + itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle); } // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function () { var allItems = []; each(this.chart.series, function (series) { var seriesOptions = series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); }); return allItems; }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items each(allItems, function (item) { legend.renderItem(item); }); // Draw the border legendWidth = options.width || legend.offsetWidth; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); if (legendBorderWidth || legendBackgroundColor) { legendWidth += padding; legendHeight += padding; if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp({ width: legendWidth, height: legendHeight }) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, lastY, allItems = this.allItems; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - this.padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function (item, i) { var y = item._legendItemPos[1], h = mathRound(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, this.padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipRect.attr({ height: clipHeight }); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipRect.attr({ height: chart.chartHeight }); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ var LegendSymbolMixin = Highcharts.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function (legend, item) { var symbolHeight = legend.options.symbolHeight || 12; item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 5 - (symbolHeight / 2), legend.symbolWidth, symbolHeight, legend.options.symbolRadius || 0 ).attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize, this.legendItem).b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled !== false) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // TODO: Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue setTimeout(runPositionItem); }); } /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ function Chart() { this.init.apply(this, arguments); } Chart.prototype = { /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data this.userOptions = userOptions; var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); chartCount++; // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = chart.colorCounter = chart.symbolCounter = 0; chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Adjust all axes tick amounts */ adjustTickAmounts: function () { if (this.options.chart.alignTicks !== false) { each(this.axes, function (axis) { axis.adjustTickAmount(); }); } this.maxTicks = null; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, hasCartesianSeries = chart.hasCartesianSeries, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // handle updated data in the series each(series, function (serie) { if (serie.isDirty) { // prepare the data so axis can read it if (serie.options.legendType === 'point') { redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } chart.adjustTickAmounts(); } chart.getMargins(); // #3098 if (hasCartesianSeries) { // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set if (axis.isDirtyExtremes) { // #821 axis.isDirtyExtremes = false; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray, axis; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); chart.adjustTickAmounts(); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Generate stacks for each series and calculate stacks total values */ getStacks: function () { var chart = this; // reset stacks for each yAxis each(chart.yAxis, function (axis) { if (axis.stacks && axis.hasVisibleSeries) { axis.oldStacks = axis.stacks; } }); each(chart.series, function (series) { if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) { series.stackKey = series.type + pick(series.options.stack, ''); } }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions, redraw) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function (redraw) { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, requiresDirtyBox, renderer = this.renderer, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(titleOptions.style.fontSize, subtitle).b }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) if (!defined(widthOption)) { chart.containerWidth = adapterRun(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = adapterRun(renderTo, 'height'); } chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(heightOption, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, optionsChart = chart.options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; // Initialize the renderer chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, optionsChart.style, true) : new Renderer(container, chartWidth, chartHeight, optionsChart.style); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function () { var chart = this, spacing = chart.spacing, axisOffset, legend = chart.legend, margin = chart.margin, legendOptions = chart.options.legend, legendMargin = pick(legendOptions.margin, 20), legendX = legendOptions.x, legendY = legendOptions.y, align = legendOptions.align, verticalAlign = legendOptions.verticalAlign, titleOffset = chart.titleOffset; chart.resetMargins(); axisOffset = chart.axisOffset; // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend if (legend.display && !legendOptions.floating) { if (align === 'right') { // horizontal alignment handled first if (!defined(margin[1])) { chart.marginRight = mathMax( chart.marginRight, legend.legendWidth - legendX + legendMargin + spacing[1] ); } } else if (align === 'left') { if (!defined(margin[3])) { chart.plotLeft = mathMax( chart.plotLeft, legend.legendWidth + legendX + legendMargin + spacing[3] ); } } else if (verticalAlign === 'top') { if (!defined(margin[0])) { chart.plotTop = mathMax( chart.plotTop, legend.legendHeight + legendY + legendMargin + spacing[0] ); } } else if (verticalAlign === 'bottom') { if (!defined(margin[2])) { chart.marginBottom = mathMax( chart.marginBottom, legend.legendHeight - legendY + legendMargin + spacing[2] ); } } } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } if (!defined(margin[3])) { chart.plotLeft += axisOffset[3]; } if (!defined(margin[0])) { chart.plotTop += axisOffset[0]; } if (!defined(margin[2])) { chart.marginBottom += axisOffset[2]; } if (!defined(margin[1])) { chart.marginRight += axisOffset[1]; } chart.setChartSize(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function (e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win, // #805 - MooTools doesn't supply e doReflow = function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }; // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && width && height && (target === win || target === doc)) { if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(chart.reflowTimeout); if (e) { // Called from window.resize chart.reflowTimeout = setTimeout(doReflow, 100); } else { // Called directly (#2224) doReflow(); } } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function () { var chart = this, reflow = function (e) { chart.reflow(e); }; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } // Resize the container with the global animation applied if enabled (#2503) (globalAnimation ? animate : css)(chart.container, { width: chartWidth + PX, height: chartHeight + PX }, globalAnimation); chart.setChartSize(true); chart.renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.layOutTitles(); // #2857 chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back // If animation is disabled, fire without delay if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2); clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this, spacing = chart.spacing, margin = chart.margin; chart.plotTop = pick(margin[0], spacing[0]); chart.marginRight = pick(margin[1], spacing[1]); chart.marginBottom = pick(margin[2], spacing[2]); chart.plotLeft = pick(margin[3], spacing[3]); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .addClass(PREFIX + 'background') .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn }) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, fill: NONE, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; } } }); }, /** * Render series for the chart */ renderSeries: function () { each(this.series, function (serie) { serie.translate(); if (serie.setTooltipPoints) { serie.setTooltipPoints(); } serie.render(); }); }, /** * Render labels for the chart */ renderLabels: function () { var chart = this, labels = chart.options.labels; if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; chart.renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); chart.getStacks(); // render stacks // Get margins by pre-rendering axes // set axes scales each(axes, function (axis) { axis.setScale(); }); chart.getMargins(); chart.maxTicks = null; // reset for second pass each(axes, function (axis) { axis.setTickPositions(true); // update to reflect the new margins axis.setMaxTicks(); }); chart.adjustTickAmounts(); chart.getMargins(); // second pass to check for new labels // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } chart.renderSeries(); // Labels chart.renderLabels(); // Credits chart.showCredits(options.credits); // Set flag chart.hasRendered = true; }, /** * Show chart credits based on config options */ showCredits: function (credits) { if (credits.enabled && !this.credits) { this.credits = this.renderer.text( credits.text, 0, 0 ) .on('click', function () { if (credits.href) { location.href = credits.href; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chartCount--; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set if (Highcharts.Pointer) { chart.pointer = new Pointer(chart, options); } chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { fn.apply(chart, [chart]); }); // If the chart was rendered outside the top container, put it back in chart.cloneRenderTo(true); fireEvent(chart, 'load'); }, /** * Creates arrays for spacing and margin from given options. */ splashArray: function (target, options) { var oVar = options[target], tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar]; return [pick(options[target + 'Top'], tArray[0]), pick(options[target + 'Right'], tArray[1]), pick(options[target + 'Bottom'], tArray[2]), pick(options[target + 'Left'], tArray[3])]; } }; // end Chart // Hook for exporting module Chart.prototype.callbacks = []; var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = { /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, slicingRoom = 2 * (options.slicedOffset || 0), handleSlicingRoom, plotWidth = chart.plotWidth - 2 * slicingRoom, plotHeight = chart.plotHeight - 2 * slicingRoom, centerOption = options.center, positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0], smallestSize = mathMin(plotWidth, plotHeight), isPercent; return map(positions, function (length, i) { isPercent = /%$/.test(length); handleSlicingRoom = i < 2 || (i === 2 && isPercent); return (isPercent ? // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 4: innerSize, relative to smallestSize [plotWidth, plotHeight, smallestSize, smallestSize][i] * pInt(length) / 100 : length) + (handleSlicingRoom ? slicingRoom : 0); }); } }; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.options.pointValKey || series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret = {}, series = this.series, pointArrayMap = series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { ret[pointArrayMap[j++]] = options[i++]; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { var point = this; return { x: point.category, y: point.y, key: point.name || point.category, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }; }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); } };/** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // Set the data each(series.parallelArrays, function (key) { series[key + 'Data'] = []; }); series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function (point, i) { var series = point.series, args = arguments, fn = typeof i === 'number' ? // Insert the value in the given position function (key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function (key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var series = this, options = series.options, xIncrement = series.xIncrement; xIncrement = pick(xIncrement, options.pointStart, 0); series.pointInterval = pick(series.pointInterval, options.pointInterval, 1); series.xIncrement = xIncrement + series.pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.plotOptions || {}, typeOptions = plotOptions[this.type], options; this.userOptions = itemOptions; options = merge( typeOptions, plotOptions.series, itemOptions ); // The tooltip options are merged between global and series specific options this.tooltipOptions = merge( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } return options; }, getCyclic: function (prop, value, defaults) { var i, userOptions = this.userOptions, indexName = '_' + prop + 'Index', counterName = prop + 'Counter'; if (!value) { if (defined(userOptions[indexName])) { // after Series.update() i = userOptions[indexName]; } else { userOptions[indexName] = i = this.chart[counterName] % defaults.length; this.chart[counterName] += 1; } value = defaults[i]; } this[prop] = value; }, /** * Get the series' color */ getColor: function () { if (!this.options.colorByPoint) { this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors); } }, /** * Get the series' symbol */ getSymbol: function () { var seriesMarkerOption = this.options.marker; this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols); // don't substract radius in image symbols (#604) if (/^url/.test(this.symbol)) { seriesMarkerOption.radius = 0; } }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, hasCategories = xAxis && !!xAxis.categories, tooltipPoints = series.tooltipPoints, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData) { each(data, function (point, i) { oldData[i].update(point, false, null, false); }); } else { // Reset properties series.xIncrement = null; series.pointRange = hasCategories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function (key) { series[key + 'Data'].length = 0; }); // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); series.updateParallelArrays(pt, i); if (hasCategories && pt.name) { xAxis.names[pt.x] = pt.name; // #2046 } } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; //series.zData = zData; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } if (tooltipPoints) { // #2594 tooltipPoints.length = 0; } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; animation = false; } if (redraw) { chart.redraw(animation); } }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, activePointCount = 0, isCartesian = series.isCartesian, xExtremes, min, max; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } if (xAxis) { xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053) min = xExtremes.min; max = xExtremes.max; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; activePointCount = processedXData.length; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i >= 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (!cropped && processedXData[i] > min && processedXData[i] < max) { activePointCount++; } if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; series.activePointCount = activePointCount; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function (xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = mathMax(0, i - cropShoulder); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (xData[i] > max) { cropEnd = i + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } points[i].index = cursor; // For faster access in Point.update } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Calculate Y extremes for visible data */ getExtremes: function (yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, dataMin, dataMax, x, y, i, j; yData = yData || this.stackedYData || this.processedYData; yDataLength = yData.length; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = pick(dataMin, arrayMin(activeYData)); this.dataMax = pick(dataMax, arrayMax(activeYData)); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = stacking && yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes if (yAxis.isLog && yValue <= 0) { point.y = yValue = null; error(10); } // Get the plotX translation point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; stackValues = pointStack.points[series.index + ',' + i]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === 0) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = pointStack.total && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ? //mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591 yAxis.translate(yValue, 0, 1, 0, 1) : UNDEFINED; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; } // now that we have the cropped data, build the segments series.getSegments(); }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, renderer = chart.renderer, clipRect, markerClipRect, animation = series.options.animation, clipBox = series.clipBox || chart.clipBox, inverted = chart.inverted, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } sharedClipKey = ['_sharedClip', animation.duration, animation.easing, clipBox.height].join(','); // Initialize the animation. Set up the clipping rectangle. if (init) { // If a clipping rectangle with the same properties is currently present in the chart, use that. clipRect = chart[sharedClipKey]; markerClipRect = chart[sharedClipKey + 'm']; if (!clipRect) { chart[sharedClipKey] = clipRect = renderer.clipRect( extend(clipBox, { width: 0 }) ); chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } series.group.clip(clipRect); series.markerGroup.clip(markerClipRect); series.sharedClipKey = sharedClipKey; // Run the animation } else { clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { var chart = this.chart, sharedClipKey = this.sharedClipKey, group = this.group, clipBox = this.clipBox; if (group && this.options.clip !== false) { if (!sharedClipKey || !clipBox) { group.clip(clipBox ? chart.renderer.clipRect(clipBox) : chart.clipRect); } this.markerGroup.clip(); // no clip } fireEvent(this, 'afterAnimate'); // Remove the shared clipping rectancgle when all series are shown setTimeout(function () { if (sharedClipKey && chart[sharedClipKey]) { if (!clipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } } }, 100); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, seriesPointAttr = series.pointAttr[''], pointMarkerOptions, hasPointMarker, enabled, isInside, markerGroup = series.markerGroup, globallyEnabled = pick( seriesMarkerOptions.enabled, !series.requireSorting || series.activePointCount < (0.5 * series.xAxis.len / seriesMarkerOptions.radius) ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; hasPointMarker = !!point.marker; enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858 // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius, hasPointMarker ? pointMarkerOptions : seriesMarkerOptions ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions = series.hasPointSpecificOptions, negativeColor = seriesOptions.negativeColor, defaultLineColor = normalOptions.lineColor, defaultFillColor = normalOptions.fillColor, turboThreshold = seriesOptions.turboThreshold, attr, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) { while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (point.negative && negativeColor) { point.color = point.fillColor = negativeColor; } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker) { // column, bar, point // If no hover color is given, brighten the normal color. #1619, #2579 pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover.color) || Color(point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness) .get(); } // normal point state inherits series wide normal state attr = { color: point.color }; // #868 if (!defaultFillColor) { // Individual point color or negative color markers (#2219) attr.fillColor = point.color; } if (!defaultLineColor) { attr.lineColor = point.color; // Bubbles take point color, line markers use white } pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(series.axisTypes || [], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // destroy all SVGElements associated to the series each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker', 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) { if (series[prop]) { // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } }); // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, (lastPoint.plotX + plotX) / 2, plotY ); } else { segmentPath.push( plotX, lastPoint.plotY ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color]], lineWidth = options.lineWidth, dashStyle = options.dashStyle, roundCap = options.linecap !== 'square', graphPath = this.getGraphPath(), negativeColor = options.negativeColor; if (negativeColor) { props.push(['graphNeg', negativeColor]); } // draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { stop(graph); // cancel running animations, #459 graph.animate({ d: graphPath }); } else if (lineWidth && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, fill: NONE, zIndex: 1 // #1069 }; if (dashStyle) { attribs.dashstyle = dashStyle; } else if (roundCap) { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow(!i && options.shadow); } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ clipNeg: function () { var options = this.options, chart = this.chart, renderer = chart.renderer, negativeColor = options.negativeColor || options.negativeFillColor, translatedThreshold, posAttr, negAttr, graph = this.graph, area = this.area, posClip = this.posClip, negClip = this.negClip, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartSizeMax = mathMax(chartWidth, chartHeight), yAxis = this.yAxis, above, below; if (negativeColor && (graph || area)) { translatedThreshold = mathRound(yAxis.toPixels(options.threshold || 0, true)); if (translatedThreshold < 0) { chartSizeMax -= translatedThreshold; // #2534 } above = { x: 0, y: 0, width: chartSizeMax, height: translatedThreshold }; below = { x: 0, y: translatedThreshold, width: chartSizeMax, height: chartSizeMax }; if (chart.inverted) { above.height = below.y = chart.plotWidth - translatedThreshold; if (renderer.isVML) { above = { x: chart.plotWidth - translatedThreshold - chart.plotLeft, y: 0, width: chartWidth, height: chartHeight }; below = { x: translatedThreshold + chart.plotLeft - chartWidth, y: 0, width: chart.plotLeft + translatedThreshold, height: chartWidth }; } } if (yAxis.reversed) { posAttr = below; negAttr = above; } else { posAttr = above; negAttr = below; } if (posClip) { // update posClip.animate(posAttr); negClip.animate(negAttr); } else { this.posClip = posClip = renderer.clipRect(posAttr); this.negClip = negClip = renderer.clipRect(negAttr); if (graph && this.graphNeg) { graph.clip(posClip); this.graphNeg.clip(negClip); } if (area) { area.clip(posClip); this.areaNeg.clip(negClip); } } } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); } // Place it on first and subsequent (redraw) calls group[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function () { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0, visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (animDuration) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.clipNeg(); } each(series.points, function (point) { if (point.redraw) { point.redraw(); } }); // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { if (animDuration) { series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animDuration); } else { series.afterAnimate(); } } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); if (series.setTooltipPoints) { series.setTooltipPoints(true); } series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } } }; // end Series prototype /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Initialize total value this.total = null; // This will keep each points' extremes stored by series.index and point index this.points = {}; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, formatOption = options.format, str = formatOption ? format(formatOption, this) : options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({text: str, visibility: HIDDEN}); // Create new label } else { this.label = this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries .css(options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, neg = this.isNegative, // special treatment is needed for negative stacks y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true); } } }; // Stacking methods defined on the Axis prototype /** * Build the stacks from top down */ Axis.prototype.buildStacks = function () { var series = this.series, reversedStacks = pick(this.options.reversedStacks, true), i = series.length; if (!this.isXAxis) { this.usePercentage = false; while (i--) { series[reversedStacks ? i : series.length - i - 1].setStackedPoints(); } // Loop up again to compute percent stack if (this.usePercentage) { for (i = 0; i < series.length; i++) { series[i].setPercentStacks(); } } } }; Axis.prototype.renderStackTotals = function () { var axis = this, chart = axis.chart, renderer = chart.renderer, stacks = axis.stacks, stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } }; // Stacking methods defnied for Series prototype /** * Adds series' points value to corresponding stack */ Series.prototype.setStackedPoints = function () { if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) { return; } var series = this, xData = series.processedXData, yData = series.processedYData, stackedYData = [], yDataLength = yData.length, seriesOptions = series.options, threshold = seriesOptions.threshold, stackOption = seriesOptions.stack, stacking = seriesOptions.stacking, stackKey = series.stackKey, negKey = '-' + stackKey, negStacks = series.negStacks, yAxis = series.yAxis, stacks = yAxis.stacks, oldStacks = yAxis.oldStacks, isNegative, stack, other, key, pointKey, i, x, y; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; pointKey = series.index + ',' + i; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) isNegative = negStacks && y < threshold; key = isNegative ? negKey : stackKey; // Create empty object for this stack if it doesn't exist yet if (!stacks[key]) { stacks[key] = {}; } // Initialize StackItem for this x if (!stacks[key][x]) { if (oldStacks[key] && oldStacks[key][x]) { stacks[key][x] = oldStacks[key][x]; stacks[key][x].total = null; } else { stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption); } } // If the StackItem doesn't exist, create it first stack = stacks[key][x]; stack.points[pointKey] = [stack.cum || 0]; // Add value to the stack total if (stacking === 'percent') { // Percent stacked column, totals are the same for the positive and negative stacks other = isNegative ? stackKey : negKey; if (negStacks && stacks[other] && stacks[other][x]) { other = stacks[other][x]; stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0; // Percent stacked areas } else { stack.total = correctFloat(stack.total + (mathAbs(y) || 0)); } } else { stack.total = correctFloat(stack.total + (y || 0)); } stack.cum = (stack.cum || 0) + (y || 0); stack.points[pointKey].push(stack.cum); stackedYData[i] = stack.cum; } if (stacking === 'percent') { yAxis.usePercentage = true; } this.stackedYData = stackedYData; // To be used in getExtremes // Reset old stacks yAxis.oldStacks = {}; }; /** * Iterate over all stacks and compute the absolute values to percent */ Series.prototype.setPercentStacks = function () { var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks, processedXData = series.processedXData; each([stackKey, '-' + stackKey], function (key) { var i = processedXData.length, x, stack, pointExtremes, totalFactor; while (i--) { x = processedXData[i]; stack = stacks[key] && stacks[key][x]; pointExtremes = stack && stack.points[series.index + ',' + i]; if (pointExtremes) { totalFactor = stack.total ? 100 / stack.total : 0; pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value series.stackedYData[i] = pointExtremes[1]; } } }); }; // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, axis; /*jslint unused: false*/ axis = new Axis(this, merge(options, { index: this[key].length, isX: isX })); /*jslint unused: true*/ // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv, loadingOptions = options.loading, setLoadingSize = function () { if (loadingDiv) { css(loadingDiv, { left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); } }; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); addEvent(chart, 'redraw', setLoadingSize); // #1080 } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } setLoadingSize(); }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation, runEvent) { var point = this, series = point.series, graphic = point.graphic, i, chart = series.chart, seriesOptions = series.options; redraw = pick(redraw, true); function update() { point.applyOptions(options); // Update visuals if (isObject(options) && !isArray(options)) { // Defer the actual redraw until getAttribs has been called (#3260) point.redraw = function () { if (graphic) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } else { graphic.attr(point.pointAttr[point.state || '']); } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } point.redraw = null; }; } // record changes in the parallel arrays i = point.index; series.updateParallelArrays(point, i); seriesOptions.data[i] = point.options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 chart.legend.destroyItem(point); } if (redraw) { chart.redraw(animation); } } // Fire the event with a default handler of doing the update if (runEvent === false) { // When called from setData update(); } else { point.firePointEvent('update', { options: options }, update); } }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var point = this, series = point.series, points = series.points, chart = series.chart, i, data = series.data; setAnimation(animation, chart); redraw = pick(redraw, true); // fire the event with a default handler of removing the point point.firePointEvent('remove', null, function () { // splice all the parallel arrays i = inArray(point, data); if (data.length === points.length) { points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.updateParallelArrays(point, 'splice', i, 1); point.destroy(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, names = series.xAxis && series.xAxis.names, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, x, i; setAnimation(animation, chart); // Make graph animate sideways if (shift) { each([graph, area, series.graphNeg, series.areaNeg], function (shape) { if (shape) { shape.shift = currentShift + 1; } }); } if (area) { area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names && point.name) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var series = this, chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, preserve = ['group', 'markerGroup', 'dataLabelsGroup'], n; // Make sure groups are not destroyed (#3094) each(preserve, function (prop) { preserve[prop] = series[prop]; delete series[prop]; }); // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and reinsert methods from the type prototype this.remove(false); for (n in proto) { // Overwrite series-type specific methods (#2270) if (proto.hasOwnProperty(n)) { this[n] = UNDEFINED; } } extend(this, seriesTypes[newOptions.type || oldType].prototype); // Re-register groups (#3094) each(preserve, function (prop) { series[prop] = preserve[prop]; }); this.init(chart, newOptions); chart.linkSeries(); // Links are lost in this.remove (#3028) if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = UNDEFINED; // #1611, #2887 this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].remove(false); } } // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); } }); /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', /** * For stacks, don't split segments on null values. Instead, draw null values with * no marker. Also insert dummy points for any X position that exists in other series * in the stack. */ getSegments: function () { var series = this, segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, connectNulls = this.options.connectNulls, i, x; if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue // Create a map where we can quickly look up the points by their X value. for (i = 0; i < points.length; i++) { pointMap[points[i].x] = points[i]; } // Sort the keys (#1651) for (x in stack) { if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336) keys.push(+x); } } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { var y = 0, stackPoint; if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836 return; // The point exists, push it to the segment } else if (pointMap[x]) { segment.push(pointMap[x]); // There is no point for this X value in this series, so we // insert a dummy point in order for the areas to be drawn // correctly. } else { // Loop down the stack to find the series below this one that has // a value (#1991) for (i = series.index; i <= yAxis.series.length; i++) { stackPoint = stack[x].points[i + ',' + x]; if (stackPoint) { y = stackPoint[1]; break; } } plotX = xAxis.translate(x); plotY = yAxis.toPixels(y, true); segment.push({ y: null, plotX: plotX, clientX: plotX, plotY: plotY, yBottom: plotY, onMouseOver: noop }); } }); if (segment.length) { segments.push(segment); } } else { Series.prototype.getSegments.call(this); segments = this.segments; } this.segments = segments; }, /** * Extend the base Series getSegmentPath method by adding the path for the area. * This path is pushed to the series.areaPath property. */ getSegmentPath: function (segment) { var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path i, options = this.options, segLength = segmentPath.length, translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181 yBottom; if (segLength === 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && !this.closedStacks) { // Follow stack back. Todo: implement areaspline. A general solution could be to // reverse the entire graphPath of the previous series, though may be hard with // splines and with series with different extremes for (i = segment.length - 1; i >= 0; i--) { yBottom = pick(segment[i].yBottom, translatedThreshold); // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, yBottom); } areaSegmentPath.push(segment[i].plotX, yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment, translatedThreshold); } this.areaPath = this.areaPath.concat(areaSegmentPath); return segmentPath; }, /** * Extendable method to close the segment path of an area. This is overridden in polar * charts. */ closeSegment: function (path, segment, translatedThreshold) { path.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var series = this, areaPath = this.areaPath, options = this.options, negativeColor = options.negativeColor, negativeFillColor = options.negativeFillColor, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color if (negativeColor || negativeFillColor) { props.push(['areaNeg', negativeColor, negativeFillColor]); } each(props, function (prop) { var areaKey = prop[0], area = series[areaKey]; // Create or update the area if (area) { // update area.animate({ d: areaPath }); } else { // create series[areaKey] = series.chart.renderer.path(areaPath) .attr({ fill: pick( prop[2], Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get() ), zIndex: 0 // #1069 }).add(series.group); } }); }, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.area = AreaSeries; /** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (lastPoint && nextPoint) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 1 }) .add(); this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 1 }) .add(); } */ // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', closedStacks: true, // instead of following the previous graph back, follow the threshold back // Mix in methods from the area series getSegmentPath: areaProto.getSegmentPath, closeSegment: areaProto.closeSegment, drawGraph: areaProto.drawGraph, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', //borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false, halo: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, stickyTracking: false, tooltip: { distance: 6 }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnIndex, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function (otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610 xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) return (series.columnMetrics = { width: pointWidth, offset: pointXOffset }); }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = series.borderWidth = pick( options.borderWidth, series.activePointCount > 0.5 * series.xAxis.len ? 0 : 1 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1; if (chart.renderer.isVML && chart.inverted) { yCrisp += 1; } // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual // columns to have individual sizes. When pointPadding is greater, we strive for equal-width // columns (#2694). if (options.pointPadding) { seriesBarW = mathCeil(seriesBarW); } Series.prototype.translate.apply(series); // Record the new values each(series.points, function (point) { var yBottom = pick(point.yBottom, translatedThreshold), plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), right, bottom, fromTop, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485) } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Fix the tooltip on center of grouped columns (#1216, #424) point.tooltipPos = chart.inverted ? [yAxis.len - plotY, series.xAxis.len - barX - barW / 2] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop]; // Round off to obtain crisp edges and avoid overlapping with neighbours (#2694) right = mathRound(barX + barW) + xCrisp; barX = mathRound(barX) + xCrisp; barW = right - barX; fromTop = mathAbs(barY) < 0.5; bottom = mathRound(barY + barH) + yCrisp; barY = mathRound(barY) + yCrisp; barH = bottom - barY; // Top edges are exceptions if (fromTop) { barY -= 1; barH += 1; } // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = { x: barX, y: barY, width: barW, height: barH }; }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs, pointAttr; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic, borderAttr; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; borderAttr = defined(series.borderWidth) ? { 'stroke-width': series.borderWidth } : {}; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE]; if (graphic) { // update stop(graphic); graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(pointAttr) .attr(borderAttr) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, tooltip: { headerFormat: '<span style="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' }, stickyTracking: false }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['markerGroup', 'dataLabelsGroup'], takeOrdinalPosition: false, // #2342 singularTooltips: true, drawGraph: function () { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: [null, null], clip: false, colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { // #2945 return this.point.name; } // softConnector: true, //y: 0 }, ignoreHiddenPoint: true, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: null, showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } }, stickyTracking: false, tooltip: { followPointer: true } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; // Disallow negative values (#1530) if (point.y < 0) { point.y = null; } //visible: options.visible !== false, extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function (e) { point.slice(e.type === 'select'); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis) { var point = this, series = point.series, chart = series.chart; // if called without an argument, toggle visibility point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data // Show and hide associated elements each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][vis ? 'show' : 'hide'](true); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // Handle ignore hidden slices if (!series.isDirty && series.options.ignoreHiddenPoint) { series.isDirty = true; chart.redraw(); } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data translation = sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; point.graphic.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } }, haloPath: function (size) { var shapeArgs = this.shapeArgs, chart = this.series.chart; return this.sliced || !this.visible ? [] : this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, { innerR: this.shapeArgs.r, start: shapeArgs.start, end: shapeArgs.end }); } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], axisTypes: [], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, singularTooltips: true, /** * Pies have one color each point */ getColor: noop, /** * Animate the pies in */ animate: function (init) { var series = this, points = series.points, startAngleRad = series.startAngleRad; if (!init) { each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: series.center[3] / 2, // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Extend the basic setData method by running processData and generatePoints immediately, * in order to access the points from the legend. */ setData: function (data, redraw, animation, updatePoints) { Series.prototype.setData.call(this, data, false, animation, updatePoints); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(animation); } }, /** * Extend the generatePoints method by adding total and percentage properties to each point */ generatePoints: function () { var i, total = 0, points, len, point, ignoreHiddenPoint = this.options.ignoreHiddenPoint; Series.prototype.generatePoints.call(this); // Populate local vars points = this.points; len = points.length; // Get the total sum for (i = 0; i < len; i++) { point = points[i]; total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } this.total = total; // Set each point's properties for (i = 0; i < len; i++) { point = points[i]; point.percentage = total > 0 ? (point.y / total) * 100 : 0; point.total = total; } }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngle = options.startAngle || 0, startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90), endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90), circ = endAngleRad - startAngleRad, //2 * mathPI, points = series.points, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // Get positions - either an integer or a percentage string must be given. // If positions are passed as a parameter, we're in a recursive loop for adjusting // space for data labels. if (!positions) { series.center = positions = series.getCenter(); } // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle start = startAngleRad + (cumulative * circ); if (!ignoreHiddenPoint || point.visible) { cumulative += point.percentage / 100; } end = startAngleRad + (cumulative * circ); // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: mathRound(start * precision) / precision, end: mathRound(end * precision) / precision }; // The angle must stay within -90 and 270 (#2645) angle = (end + start) / 2; if (angle > 1.5 * mathPI) { angle -= 2 * mathPI; } else if (angle < -mathPI / 2) { angle += 2 * mathPI; } // Center for the sliced out slice point.slicedTranslation = { translateX: mathRound(mathCos(angle) * slicedOffset), translateY: mathRound(mathSin(angle) * slicedOffset) }; // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0; point.angle = angle; // set the anchor point for data labels connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678 point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; } }, drawGraph: null, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, //group, shadow = series.options.shadow, shadowGroup, shapeArgs; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { graphic = point.graphic; shapeArgs = point.shapeArgs; shadowGroup = point.shadowGroup; // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .add(series.shadowGroup); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; //group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.attr(groupTranslation); } // draw the slice if (graphic) { graphic.animate(extend(shapeArgs, groupTranslation)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr({ 'stroke-linejoin': 'round' //zIndex: 1 // #2722 (reversed) }) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } // detect point specific visibility (#2430) if (point.visible !== undefined) { point.setVisible(point.visible); } }); }, /** * Utility for sorting data labels */ sortByAngle: function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }, /** * Use a simple symbol from LegendSymbolMixin */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Use the getCenter method from drawLegendSymbol */ getCenter: CenteredSeriesMixin.getCenter, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; /** * Draw the data labels */ Series.prototype.drawDataLabels = function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, hasRendered = series.hasRendered || 0, str, dataLabelsGroup; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', options.defer ? HIDDEN : VISIBLE, options.zIndex || 6 ); if (pick(options.defer, true)) { dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300 if (!hasRendered) { addEvent(series, 'afterAnimate', function () { if (series.visible) { // #3023, #3024 dataLabelsGroup.show(); } dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } } // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true; // Determine if each data label is enabled pointOptions = point.options && point.options.dataLabels; enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color options.style.color = pick(options.color, options.style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, null, null, null, options.useHTML ) .attr(attr) .css(extend(options.style, cursor && { cursor: cursor })) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }; /** * Align each individual data label */ Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))), alignAttr; // the final position; if (visible) { // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text dataLabel[isNew ? 'attr' : 'animate']({ x: alignTo.x + options.x + alignTo.width / 2, y: alignTo.y + options.y + alignTo.height / 2 }) .attr({ // #3003 align: options.align }); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; // Handle justify or crop if (pick(options.overflow, 'justify') === 'justify') { this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); } else if (pick(options.crop, true)) { // Now check that the data label is within the plot area visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } } } // Show or hide based on the final aligned position if (!visible) { dataLabel.attr({ y: -999 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified; // Off left off = alignAttr.x; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.drawDataLabels = function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel && point.visible) { // #407, #2510 halves[point.half].push(point); } }); /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, bottom, length = points.length, slotIndex; if (!length) { continue; } // Sort by angle series.sortByAngle(points, i - 0.5); // Assume equal label heights on either hemisphere (#2630) j = labelHeight = 0; while (!labelHeight && points[j]) { // #1569 labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968 j++; } // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // Build the slots bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight); for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) { slots.push(pos); } slotsLength = slots.length; /* Visualize the slots if (!series.slotElements) { series.slotElements = []; } if (i === 1) { series.slotElements.forEach(function (elem) { elem.destroy(); }); series.slotElements.length = 0; } slots.forEach(function (pos, no) { var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver', fill: 'rgba(0,0,255,0.1)' }) .add()); series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4) .attr({ fill: 'silver' }).add()); } }); // */ // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : VISIBLE; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = mathMin(mathMax(0, naturalY), chart.plotHeight); } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility //zIndex: 0 // #2722 (reversed) }) .add(series.dataLabelsGroup); } } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.placeDataLabels = function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)), inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (inverted) { alignTo = { x: chart.plotWidth - alignTo.y - alignTo.height, y: chart.plotHeight - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }; } /** * TrackerMixin for points and graphs */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; if (chart.hoverSeries !== series) { series.onMouseOver(); } while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; /* End TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) { var legend = this; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); legendItem.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { legendItem.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { item.setVisible(); }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); }, createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function () { item.select(); } ); }); } }); /* * Add pointer cursor to legend itemstyle in defaultOptions */ defaultOptions.legend.itemStyle.cursor = 'pointer'; /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps var mousePos = e[isX ? 'chartX' : 'chartY'], axis = chart[isX ? 'xAxis' : 'yAxis'][0], startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange; if (axis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; this.firePointEvent('mouseOut'); if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240 this.setState(); chart.hoverPoint = null; } }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state, move) { var point = this, plotX = point.plotX, plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, halo = series.halo, haloOptions, newSymbol, pointAttr; state = state || NORMAL_STATE; // empty string pointAttr = point.pointAttr[state] || series.pointAttr[state]; if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr.r; point.graphic.attr(merge( pointAttr, radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 } } // Show me your halo haloOptions = stateOptions[state] && stateOptions[state].halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(series.seriesGroup); } halo.attr(extend({ fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get() }, haloOptions.attributes))[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); } else if (halo) { halo.attr({ d: [] }); } point.state = state; }, haloPath: function (size) { var series = this.series, chart = series.chart, plotBox = series.getPlotBox(), inverted = chart.inverted; return chart.renderer.symbols.circle( plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size, plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); chart.hoverSeries = null; }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, graphNeg = series.graphNeg, stateOptions = options.states, lineWidth = options.lineWidth, attribs; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0); } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); if (graphNeg) { graphNeg.attr(attribs); } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Memorize tooltip texts and positions */ setTooltipPoints: function (renew) { var series = this, points = [], pointsLength, low, high, xAxis = series.xAxis, xExtremes = xAxis && xAxis.getExtremes(), axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar point, pointX, nextPoint, i, tooltipPoints = []; // a lookup array for each pixel in the x dimension // don't waste resources if tracker is disabled if (series.options.enableMouseTracking === false || series.singularTooltips) { return; } // renew if (renew) { series.tooltipPoints = null; } // concat segments to overcome null values each(series.segments || series.points, function (segment) { points = points.concat(segment); }); // Reverse the points in case the X axis is reversed if (xAxis && xAxis.reversed) { points = points.reverse(); } // Polar needs additional shaping if (series.orderTooltipPoints) { series.orderTooltipPoints(points); } // Assign each pixel position to the nearest point pointsLength = points.length; for (i = 0; i < pointsLength; i++) { point = points[i]; pointX = point.x; if (pointX >= xExtremes.min && pointX <= xExtremes.max) { // #1149 nextPoint = points[i + 1]; // Set this range's low to the last range's high plus one low = high === UNDEFINED ? 0 : high + 1; // Now find the new high high = points[i + 1] ? mathMin(mathMax(0, mathFloor( // #2070 (point.clientX + (nextPoint ? (nextPoint.wrappedClientX || nextPoint.clientX) : axisLength)) / 2 )), axisLength) : axisLength; while (low >= 0 && low <= high) { tooltipPoints[low++] = point; } } } series.tooltipPoints = tooltipPoints; }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, drawTracker: TrackerMixin.drawTrackerGraph }); // global variables extend(Highcharts, { // Constructors Axis: Axis, Chart: Chart, Color: Color, Point: Point, Tick: Tick, Renderer: Renderer, Series: Series, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, numberFormat: numberFormat, seriesTypes: seriesTypes, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, extend: extend, map: map, merge: merge, pick: pick, splat: splat, extendClass: extendClass, pInt: pInt, wrap: wrap, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
src/components/search-page/SearchForm.js
AnisaIshmail/IdeaZone
// Using inline searchform instead // import React, { Component } from 'react'; // class SearchForm extends Component { // render() { // return ( // <div> // <header className="text-center clearfix"> // <h1>Find Project Ideas or Add an Idea<i className="fa fa-plus-circle float-right" data-toggle="modal" data-target="#addIdeaModal" aria-hidden="true" title="Add an idea"></i></h1> // </header> // <div id="search-input"> // <div className="input-group col-md-12"> // <input type="text" className="form-control input-lg" placeholder="Search" /> // <span className="input-group-btn"> // <button className="btn btn-default btn-lg" type="button"> // <i className="fa fa-search" aria-hidden="true"></i> // </button> // </span> // </div> // </div> // </div> // ); // } // } // export default SearchForm;
App/node_modules/metro-bundler/node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/expected.js
Dagers/React-Native-Differential-Updater
import React from 'react'; const First = React.createNotClass({ displayName: 'First' }); class Second extends React.NotComponent {}
ajax/libs/onsen/1.3.11/js/onsenui.js
dannyxx001/cdnjs
/*! onsenui - v1.3.11 - 2015-09-28 */ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // JavaScript Dynamic Content shim for Windows Store apps (function () { if (window.MSApp && MSApp.execUnsafeLocalFunction) { // Some nodes will have an "attributes" property which shadows the Node.prototype.attributes property // and means we don't actually see the attributes of the Node (interestingly the VS debug console // appears to suffer from the same issue). // var Element_setAttribute = Object.getOwnPropertyDescriptor(Element.prototype, "setAttribute").value; var Element_removeAttribute = Object.getOwnPropertyDescriptor(Element.prototype, "removeAttribute").value; var HTMLElement_insertAdjacentHTMLPropertyDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "insertAdjacentHTML"); var Node_get_attributes = Object.getOwnPropertyDescriptor(Node.prototype, "attributes").get; var Node_get_childNodes = Object.getOwnPropertyDescriptor(Node.prototype, "childNodes").get; var detectionDiv = document.createElement("div"); function getAttributes(element) { return Node_get_attributes.call(element); } function setAttribute(element, attribute, value) { try { Element_setAttribute.call(element, attribute, value); } catch (e) { // ignore } } function removeAttribute(element, attribute) { Element_removeAttribute.call(element, attribute); } function childNodes(element) { return Node_get_childNodes.call(element); } function empty(element) { while (element.childNodes.length) { element.removeChild(element.lastChild); } } function insertAdjacentHTML(element, position, html) { HTMLElement_insertAdjacentHTMLPropertyDescriptor.value.call(element, position, html); } function inUnsafeMode() { var isUnsafe = true; try { detectionDiv.innerHTML = "<test/>"; } catch (ex) { isUnsafe = false; } return isUnsafe; } function cleanse(html, targetElement) { var cleaner = document.implementation.createHTMLDocument("cleaner"); empty(cleaner.documentElement); MSApp.execUnsafeLocalFunction(function () { insertAdjacentHTML(cleaner.documentElement, "afterbegin", html); }); var scripts = cleaner.documentElement.querySelectorAll("script"); Array.prototype.forEach.call(scripts, function (script) { switch (script.type.toLowerCase()) { case "": script.type = "text/inert"; break; case "text/javascript": case "text/ecmascript": case "text/x-javascript": case "text/jscript": case "text/livescript": case "text/javascript1.1": case "text/javascript1.2": case "text/javascript1.3": script.type = "text/inert-" + script.type.slice("text/".length); break; case "application/javascript": case "application/ecmascript": case "application/x-javascript": script.type = "application/inert-" + script.type.slice("application/".length); break; default: break; } }); function cleanseAttributes(element) { var attributes = getAttributes(element); if (attributes && attributes.length) { // because the attributes collection is live it is simpler to queue up the renames var events; for (var i = 0, len = attributes.length; i < len; i++) { var attribute = attributes[i]; var name = attribute.name; if ((name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) { events = events || []; events.push({ name: attribute.name, value: attribute.value }); } } if (events) { for (var i = 0, len = events.length; i < len; i++) { var attribute = events[i]; removeAttribute(element, attribute.name); setAttribute(element, "x-" + attribute.name, attribute.value); } } } var children = childNodes(element); for (var i = 0, len = children.length; i < len; i++) { cleanseAttributes(children[i]); } } cleanseAttributes(cleaner.documentElement); var cleanedNodes = []; if (targetElement.tagName === 'HTML') { cleanedNodes = Array.prototype.slice.call(document.adoptNode(cleaner.documentElement).childNodes); } else { if (cleaner.head) { cleanedNodes = cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.head).childNodes)); } if (cleaner.body) { cleanedNodes = cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.body).childNodes)); } } return cleanedNodes; } function cleansePropertySetter(property, setter) { var propertyDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, property); var originalSetter = propertyDescriptor.set; Object.defineProperty(HTMLElement.prototype, property, { get: propertyDescriptor.get, set: function (value) { if(window.WinJS && window.WinJS._execUnsafe && inUnsafeMode()) { originalSetter.call(this, value); } else { var that = this; var nodes = cleanse(value, that); MSApp.execUnsafeLocalFunction(function () { setter(propertyDescriptor, that, nodes); }); } }, enumerable: propertyDescriptor.enumerable, configurable: propertyDescriptor.configurable, }); } cleansePropertySetter("innerHTML", function (propertyDescriptor, target, elements) { empty(target); for (var i = 0, len = elements.length; i < len; i++) { target.appendChild(elements[i]); } }); cleansePropertySetter("outerHTML", function (propertyDescriptor, target, elements) { for (var i = 0, len = elements.length; i < len; i++) { target.insertAdjacentElement("afterend", elements[i]); } target.parentNode.removeChild(target); }); } }()); /* Simple JavaScript Inheritance * By John Resig http://ejohn.org/ * MIT Licensed. */ // Inspired by base2 and Prototype (function(){ var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) this.Class = function(){}; // Create a new Class that inherits from this class Class.extend = function(prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var prototype = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn){ return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if ( !initializing && this.init ) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = prototype; // Enforce the constructor to be what we expect Class.prototype.constructor = Class; // And make this class extendable Class.extend = arguments.callee; return Class; }; })(); ;(function () { 'use strict'; /** * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs. * * @codingstandard ftlabs-jsv2 * @copyright The Financial Times Limited [All Rights Reserved] * @license MIT License (see LICENSE.txt) */ /*jslint browser:true, node:true*/ /*global define, Event, Node*/ /** * Instantiate fast-clicking listeners on the specified layer. * * @constructor * @param {Element} layer The layer to listen on * @param {Object} [options={}] The options to override the defaults */ function FastClick(layer, options) { var oldOnClick; options = options || {}; /** * Whether a click is currently being tracked. * * @type boolean */ this.trackingClick = false; /** * Timestamp for when click tracking started. * * @type number */ this.trackingClickStart = 0; /** * The element being tracked for a click. * * @type EventTarget */ this.targetElement = null; /** * X-coordinate of touch start event. * * @type number */ this.touchStartX = 0; /** * Y-coordinate of touch start event. * * @type number */ this.touchStartY = 0; /** * ID of the last touch, retrieved from Touch.identifier. * * @type number */ this.lastTouchIdentifier = 0; /** * Touchmove boundary, beyond which a click will be cancelled. * * @type number */ this.touchBoundary = options.touchBoundary || 10; /** * The FastClick layer. * * @type Element */ this.layer = layer; /** * The minimum time between tap(touchstart and touchend) events * * @type number */ this.tapDelay = options.tapDelay || 200; /** * The maximum time for a tap * * @type number */ this.tapTimeout = options.tapTimeout || 700; if (FastClick.notNeeded(layer)) { return; } // Some old versions of Android don't have Function.prototype.bind function bind(method, context) { return function() { return method.apply(context, arguments); }; } var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel']; var context = this; for (var i = 0, l = methods.length; i < l; i++) { context[methods[i]] = bind(context[methods[i]], context); } // Set up event handlers as required if (deviceIsAndroid) { layer.addEventListener('mouseover', this.onMouse, true); layer.addEventListener('mousedown', this.onMouse, true); layer.addEventListener('mouseup', this.onMouse, true); } layer.addEventListener('click', this.onClick, true); layer.addEventListener('touchstart', this.onTouchStart, false); layer.addEventListener('touchmove', this.onTouchMove, false); layer.addEventListener('touchend', this.onTouchEnd, false); layer.addEventListener('touchcancel', this.onTouchCancel, false); // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick // layer when they are cancelled. if (!Event.prototype.stopImmediatePropagation) { layer.removeEventListener = function(type, callback, capture) { var rmv = Node.prototype.removeEventListener; if (type === 'click') { rmv.call(layer, type, callback.hijacked || callback, capture); } else { rmv.call(layer, type, callback, capture); } }; layer.addEventListener = function(type, callback, capture) { var adv = Node.prototype.addEventListener; if (type === 'click') { adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) { if (!event.propagationStopped) { callback(event); } }), capture); } else { adv.call(layer, type, callback, capture); } }; } // If a handler is already declared in the element's onclick attribute, it will be fired before // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and // adding it as listener. if (typeof layer.onclick === 'function') { // Android browser on at least 3.2 requires a new reference to the function in layer.onclick // - the old one won't work if passed to addEventListener directly. oldOnClick = layer.onclick; layer.addEventListener('click', function(event) { oldOnClick(event); }, false); layer.onclick = null; } } /** * Windows Phone 8.1 fakes user agent string to look like Android and iPhone. * * @type boolean */ var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0; /** * Android requires exceptions. * * @type boolean */ var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone; /** * iOS requires exceptions. * * @type boolean */ var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone; /** * iOS 4 requires an exception for select elements. * * @type boolean */ var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent); /** * iOS 6.0-7.* requires the target element to be manually derived * * @type boolean */ var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent); /** * BlackBerry requires exceptions. * * @type boolean */ var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0; /** * Determine whether a given element requires a native click. * * @param {EventTarget|Element} target Target DOM element * @returns {boolean} Returns true if the element needs a native click */ FastClick.prototype.needsClick = function(target) { switch (target.nodeName.toLowerCase()) { // Don't send a synthetic click to disabled inputs (issue #62) case 'button': case 'select': case 'textarea': if (target.disabled) { return true; } break; case 'input': // File inputs need real clicks on iOS 6 due to a browser bug (issue #68) if ((deviceIsIOS && target.type === 'file') || target.disabled) { return true; } break; case 'label': case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames case 'video': return true; } return (/\bneedsclick\b/).test(target.className); }; /** * Determine whether a given element requires a call to focus to simulate click into element. * * @param {EventTarget|Element} target Target DOM element * @returns {boolean} Returns true if the element requires a call to focus to simulate native click. */ FastClick.prototype.needsFocus = function(target) { switch (target.nodeName.toLowerCase()) { case 'textarea': return true; case 'select': return !deviceIsAndroid; case 'input': switch (target.type) { case 'button': case 'checkbox': case 'file': case 'image': case 'radio': case 'submit': return false; } // No point in attempting to focus disabled inputs return !target.disabled && !target.readOnly; default: return (/\bneedsfocus\b/).test(target.className); } }; /** * Send a click event to the specified element. * * @param {EventTarget|Element} targetElement * @param {Event} event */ FastClick.prototype.sendClick = function(targetElement, event) { var clickEvent, touch; // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24) if (document.activeElement && document.activeElement !== targetElement) { document.activeElement.blur(); } touch = event.changedTouches[0]; // Synthesise a click event, with an extra attribute so it can be tracked clickEvent = document.createEvent('MouseEvents'); clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null); clickEvent.forwardedTouchEvent = true; targetElement.dispatchEvent(clickEvent); }; FastClick.prototype.determineEventType = function(targetElement) { //Issue #159: Android Chrome Select Box does not open with a synthetic click event if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') { return 'mousedown'; } return 'click'; }; /** * @param {EventTarget|Element} targetElement */ FastClick.prototype.focus = function(targetElement) { var length; // Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724. if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') { length = targetElement.value.length; targetElement.setSelectionRange(length, length); } else { targetElement.focus(); } }; /** * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it. * * @param {EventTarget|Element} targetElement */ FastClick.prototype.updateScrollParent = function(targetElement) { var scrollParent, parentElement; scrollParent = targetElement.fastClickScrollParent; // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the // target element was moved to another parent. if (!scrollParent || !scrollParent.contains(targetElement)) { parentElement = targetElement; do { if (parentElement.scrollHeight > parentElement.offsetHeight) { scrollParent = parentElement; targetElement.fastClickScrollParent = parentElement; break; } parentElement = parentElement.parentElement; } while (parentElement); } // Always update the scroll top tracker if possible. if (scrollParent) { scrollParent.fastClickLastScrollTop = scrollParent.scrollTop; } }; /** * @param {EventTarget} targetElement * @returns {Element|EventTarget} */ FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) { // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node. if (eventTarget.nodeType === Node.TEXT_NODE) { return eventTarget.parentNode; } return eventTarget; }; /** * On touch start, record the position and scroll offset. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchStart = function(event) { var targetElement, touch, selection; // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111). if (event.targetTouches.length > 1) { return true; } targetElement = this.getTargetElementFromEventTarget(event.target); touch = event.targetTouches[0]; if (deviceIsIOS) { // Only trusted events will deselect text on iOS (issue #49) selection = window.getSelection(); if (selection.rangeCount && !selection.isCollapsed) { return true; } if (!deviceIsIOS4) { // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23): // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched // with the same identifier as the touch event that previously triggered the click that triggered the alert. // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform. // Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string, // which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long, // random integers, it's safe to to continue if the identifier is 0 here. if (touch.identifier && touch.identifier === this.lastTouchIdentifier) { event.preventDefault(); return false; } this.lastTouchIdentifier = touch.identifier; // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and: // 1) the user does a fling scroll on the scrollable layer // 2) the user stops the fling scroll with another tap // then the event.target of the last 'touchend' event will be the element that was under the user's finger // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42). this.updateScrollParent(targetElement); } } this.trackingClick = true; this.trackingClickStart = event.timeStamp; this.targetElement = targetElement; this.touchStartX = touch.pageX; this.touchStartY = touch.pageY; // Prevent phantom clicks on fast double-tap (issue #36) if ((event.timeStamp - this.lastClickTime) < this.tapDelay && (event.timeStamp - this.lastClickTime) > -1) { event.preventDefault(); } return true; }; /** * Based on a touchmove event object, check whether the touch has moved past a boundary since it started. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.touchHasMoved = function(event) { var touch = event.changedTouches[0], boundary = this.touchBoundary; if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) { return true; } return false; }; /** * Update the last position. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchMove = function(event) { if (!this.trackingClick) { return true; } // If the touch has moved, cancel the click tracking if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) { this.trackingClick = false; this.targetElement = null; } return true; }; /** * Attempt to find the labelled control for the given label element. * * @param {EventTarget|HTMLLabelElement} labelElement * @returns {Element|null} */ FastClick.prototype.findControl = function(labelElement) { // Fast path for newer browsers supporting the HTML5 control attribute if (labelElement.control !== undefined) { return labelElement.control; } // All browsers under test that support touch events also support the HTML5 htmlFor attribute if (labelElement.htmlFor) { return document.getElementById(labelElement.htmlFor); } // If no for attribute exists, attempt to retrieve the first labellable descendant element // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea'); }; /** * On touch end, determine whether to send a click event at once. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchEnd = function(event) { var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement; if (!this.trackingClick) { return true; } // Prevent phantom clicks on fast double-tap (issue #36) if ((event.timeStamp - this.lastClickTime) < this.tapDelay && (event.timeStamp - this.lastClickTime) > -1) { this.cancelNextClick = true; return true; } if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) { return true; } // Reset to prevent wrong click cancel on input (issue #156). this.cancelNextClick = false; this.lastClickTime = event.timeStamp; trackingClickStart = this.trackingClickStart; this.trackingClick = false; this.trackingClickStart = 0; // On some iOS devices, the targetElement supplied with the event is invalid if the layer // is performing a transition or scroll, and has to be re-detected manually. Note that // for this to function correctly, it must be called *after* the event target is checked! // See issue #57; also filed as rdar://13048589 . if (deviceIsIOSWithBadTarget) { touch = event.changedTouches[0]; // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement; targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent; } targetTagName = targetElement.tagName.toLowerCase(); if (targetTagName === 'label') { forElement = this.findControl(targetElement); if (forElement) { this.focus(targetElement); if (deviceIsAndroid) { return false; } targetElement = forElement; } } else if (this.needsFocus(targetElement)) { // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through. // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37). if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) { this.targetElement = null; return false; } this.focus(targetElement); this.sendClick(targetElement, event); // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open. // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others) if (!deviceIsIOS || targetTagName !== 'select') { this.targetElement = null; event.preventDefault(); } return false; } if (deviceIsIOS && !deviceIsIOS4) { // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42). scrollParent = targetElement.fastClickScrollParent; if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) { return true; } } // Prevent the actual click from going though - unless the target node is marked as requiring // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted. if (!this.needsClick(targetElement)) { event.preventDefault(); this.sendClick(targetElement, event); } return false; }; /** * On touch cancel, stop tracking the click. * * @returns {void} */ FastClick.prototype.onTouchCancel = function() { this.trackingClick = false; this.targetElement = null; }; /** * Determine mouse events which should be permitted. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onMouse = function(event) { // If a target element was never set (because a touch event was never fired) allow the event if (!this.targetElement) { return true; } if (event.forwardedTouchEvent) { return true; } // Programmatically generated events targeting a specific element should be permitted if (!event.cancelable) { return true; } // Derive and check the target element to see whether the mouse event needs to be permitted; // unless explicitly enabled, prevent non-touch click events from triggering actions, // to prevent ghost/doubleclicks. if (!this.needsClick(this.targetElement) || this.cancelNextClick) { // Prevent any user-added listeners declared on FastClick element from being fired. if (event.stopImmediatePropagation) { event.stopImmediatePropagation(); } else { // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) event.propagationStopped = true; } // Cancel the event event.stopPropagation(); event.preventDefault(); return false; } // If the mouse event is permitted, return true for the action to go through. return true; }; /** * On actual clicks, determine whether this is a touch-generated click, a click action occurring * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or * an actual click which should be permitted. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onClick = function(event) { var permitted; // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early. if (this.trackingClick) { this.targetElement = null; this.trackingClick = false; return true; } // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target. if (event.target.type === 'submit' && event.detail === 0) { return true; } permitted = this.onMouse(event); // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through. if (!permitted) { this.targetElement = null; } // If clicks are permitted, return true for the action to go through. return permitted; }; /** * Remove all FastClick's event listeners. * * @returns {void} */ FastClick.prototype.destroy = function() { var layer = this.layer; if (deviceIsAndroid) { layer.removeEventListener('mouseover', this.onMouse, true); layer.removeEventListener('mousedown', this.onMouse, true); layer.removeEventListener('mouseup', this.onMouse, true); } layer.removeEventListener('click', this.onClick, true); layer.removeEventListener('touchstart', this.onTouchStart, false); layer.removeEventListener('touchmove', this.onTouchMove, false); layer.removeEventListener('touchend', this.onTouchEnd, false); layer.removeEventListener('touchcancel', this.onTouchCancel, false); }; /** * Check whether FastClick is needed. * * @param {Element} layer The layer to listen on */ FastClick.notNeeded = function(layer) { var metaViewport; var chromeVersion; var blackberryVersion; var firefoxVersion; // Devices that don't support touch don't need FastClick if (typeof window.ontouchstart === 'undefined') { return true; } // Chrome version - zero for other browsers chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1]; if (chromeVersion) { if (deviceIsAndroid) { metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport) { // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89) if (metaViewport.content.indexOf('user-scalable=no') !== -1) { return true; } // Chrome 32 and above with width=device-width or less don't need FastClick if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) { return true; } } // Chrome desktop doesn't need FastClick (issue #15) } else { return true; } } if (deviceIsBlackBerry10) { blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/); // BlackBerry 10.3+ does not require Fastclick library. // https://github.com/ftlabs/fastclick/issues/251 if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) { metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport) { // user-scalable=no eliminates click delay. if (metaViewport.content.indexOf('user-scalable=no') !== -1) { return true; } // width=device-width (or less than device-width) eliminates click delay. if (document.documentElement.scrollWidth <= window.outerWidth) { return true; } } } } // IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97) if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') { return true; } // Firefox version - zero for other browsers firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1]; if (firefoxVersion >= 27) { // Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896 metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) { return true; } } // IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version // http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') { return true; } return false; }; /** * Factory method for creating a FastClick object * * @param {Element} layer The layer to listen on * @param {Object} [options={}] The options to override the defaults */ FastClick.attach = function(layer, options) { return new FastClick(layer, options); }; if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { // AMD. Register as an anonymous module. define(function() { return FastClick; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = FastClick.attach; module.exports.FastClick = FastClick; } else { window.FastClick = FastClick; } }()); /*! Hammer.JS - v1.1.3 - 2014-05-20 * http://eightmedia.github.io/hammer.js * * Copyright (c) 2014 Jorik Tangelder <[email protected]>; * Licensed under the MIT license */ (function(window, undefined) { 'use strict'; /** * @main * @module hammer * * @class Hammer * @static */ /** * Hammer, use this to create instances * ```` * var hammertime = new Hammer(myElement); * ```` * * @method Hammer * @param {HTMLElement} element * @param {Object} [options={}] * @return {Hammer.Instance} */ var Hammer = function Hammer(element, options) { return new Hammer.Instance(element, options || {}); }; /** * version, as defined in package.json * the value will be set at each build * @property VERSION * @final * @type {String} */ Hammer.VERSION = '1.1.3'; /** * default settings. * more settings are defined per gesture at `/gestures`. Each gesture can be disabled/enabled * by setting it's name (like `swipe`) to false. * You can set the defaults for all instances by changing this object before creating an instance. * @example * ```` * Hammer.defaults.drag = false; * Hammer.defaults.behavior.touchAction = 'pan-y'; * delete Hammer.defaults.behavior.userSelect; * ```` * @property defaults * @type {Object} */ Hammer.defaults = { /** * this setting object adds styles and attributes to the element to prevent the browser from doing * its native behavior. The css properties are auto prefixed for the browsers when needed. * @property defaults.behavior * @type {Object} */ behavior: { /** * Disables text selection to improve the dragging gesture. When the value is `none` it also sets * `onselectstart=false` for IE on the element. Mainly for desktop browsers. * @property defaults.behavior.userSelect * @type {String} * @default 'none' */ userSelect: 'none', /** * Specifies whether and how a given region can be manipulated by the user (for instance, by panning or zooming). * Used by Chrome 35> and IE10>. By default this makes the element blocking any touch event. * @property defaults.behavior.touchAction * @type {String} * @default: 'pan-y' */ touchAction: 'pan-y', /** * Disables the default callout shown when you touch and hold a touch target. * On iOS, when you touch and hold a touch target such as a link, Safari displays * a callout containing information about the link. This property allows you to disable that callout. * @property defaults.behavior.touchCallout * @type {String} * @default 'none' */ touchCallout: 'none', /** * Specifies whether zooming is enabled. Used by IE10> * @property defaults.behavior.contentZooming * @type {String} * @default 'none' */ contentZooming: 'none', /** * Specifies that an entire element should be draggable instead of its contents. * Mainly for desktop browsers. * @property defaults.behavior.userDrag * @type {String} * @default 'none' */ userDrag: 'none', /** * Overrides the highlight color shown when the user taps a link or a JavaScript * clickable element in Safari on iPhone. This property obeys the alpha value, if specified. * * If you don't specify an alpha value, Safari on iPhone applies a default alpha value * to the color. To disable tap highlighting, set the alpha value to 0 (invisible). * If you set the alpha value to 1.0 (opaque), the element is not visible when tapped. * @property defaults.behavior.tapHighlightColor * @type {String} * @default 'rgba(0,0,0,0)' */ tapHighlightColor: 'rgba(0,0,0,0)' } }; /** * hammer document where the base events are added at * @property DOCUMENT * @type {HTMLElement} * @default window.document */ Hammer.DOCUMENT = document; /** * detect support for pointer events * @property HAS_POINTEREVENTS * @type {Boolean} */ Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled; /** * detect support for touch events * @property HAS_TOUCHEVENTS * @type {Boolean} */ Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window); /** * detect mobile browsers * @property IS_MOBILE * @type {Boolean} */ Hammer.IS_MOBILE = /mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent); /** * detect if we want to support mouseevents at all * @property NO_MOUSEEVENTS * @type {Boolean} */ Hammer.NO_MOUSEEVENTS = (Hammer.HAS_TOUCHEVENTS && Hammer.IS_MOBILE) || Hammer.HAS_POINTEREVENTS; /** * interval in which Hammer recalculates current velocity/direction/angle in ms * @property CALCULATE_INTERVAL * @type {Number} * @default 25 */ Hammer.CALCULATE_INTERVAL = 25; /** * eventtypes per touchevent (start, move, end) are filled by `Event.determineEventTypes` on `setup` * the object contains the DOM event names per type (`EVENT_START`, `EVENT_MOVE`, `EVENT_END`) * @property EVENT_TYPES * @private * @writeOnce * @type {Object} */ var EVENT_TYPES = {}; /** * direction strings, for safe comparisons * @property DIRECTION_DOWN|LEFT|UP|RIGHT * @final * @type {String} * @default 'down' 'left' 'up' 'right' */ var DIRECTION_DOWN = Hammer.DIRECTION_DOWN = 'down'; var DIRECTION_LEFT = Hammer.DIRECTION_LEFT = 'left'; var DIRECTION_UP = Hammer.DIRECTION_UP = 'up'; var DIRECTION_RIGHT = Hammer.DIRECTION_RIGHT = 'right'; /** * pointertype strings, for safe comparisons * @property POINTER_MOUSE|TOUCH|PEN * @final * @type {String} * @default 'mouse' 'touch' 'pen' */ var POINTER_MOUSE = Hammer.POINTER_MOUSE = 'mouse'; var POINTER_TOUCH = Hammer.POINTER_TOUCH = 'touch'; var POINTER_PEN = Hammer.POINTER_PEN = 'pen'; /** * eventtypes * @property EVENT_START|MOVE|END|RELEASE|TOUCH * @final * @type {String} * @default 'start' 'change' 'move' 'end' 'release' 'touch' */ var EVENT_START = Hammer.EVENT_START = 'start'; var EVENT_MOVE = Hammer.EVENT_MOVE = 'move'; var EVENT_END = Hammer.EVENT_END = 'end'; var EVENT_RELEASE = Hammer.EVENT_RELEASE = 'release'; var EVENT_TOUCH = Hammer.EVENT_TOUCH = 'touch'; /** * if the window events are set... * @property READY * @writeOnce * @type {Boolean} * @default false */ Hammer.READY = false; /** * plugins namespace * @property plugins * @type {Object} */ Hammer.plugins = Hammer.plugins || {}; /** * gestures namespace * see `/gestures` for the definitions * @property gestures * @type {Object} */ Hammer.gestures = Hammer.gestures || {}; /** * setup events to detect gestures on the document * this function is called when creating an new instance * @private */ function setup() { if(Hammer.READY) { return; } // find what eventtypes we add listeners to Event.determineEventTypes(); // Register all gestures inside Hammer.gestures Utils.each(Hammer.gestures, function(gesture) { Detection.register(gesture); }); // Add touch events on the document Event.onTouch(Hammer.DOCUMENT, EVENT_MOVE, Detection.detect); Event.onTouch(Hammer.DOCUMENT, EVENT_END, Detection.detect); // Hammer is ready...! Hammer.READY = true; } /** * @module hammer * * @class Utils * @static */ var Utils = Hammer.utils = { /** * extend method, could also be used for cloning when `dest` is an empty object. * changes the dest object * @method extend * @param {Object} dest * @param {Object} src * @param {Boolean} [merge=false] do a merge * @return {Object} dest */ extend: function extend(dest, src, merge) { for(var key in src) { if(!src.hasOwnProperty(key) || (dest[key] !== undefined && merge)) { continue; } dest[key] = src[key]; } return dest; }, /** * simple addEventListener wrapper * @method on * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ on: function on(element, type, handler) { element.addEventListener(type, handler, false); }, /** * simple removeEventListener wrapper * @method off * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ off: function off(element, type, handler) { element.removeEventListener(type, handler, false); }, /** * forEach over arrays and objects * @method each * @param {Object|Array} obj * @param {Function} iterator * @param {any} iterator.item * @param {Number} iterator.index * @param {Object|Array} iterator.obj the source object * @param {Object} context value to use as `this` in the iterator */ each: function each(obj, iterator, context) { var i, len; // native forEach on arrays if('forEach' in obj) { obj.forEach(iterator, context); // arrays } else if(obj.length !== undefined) { for(i = 0, len = obj.length; i < len; i++) { if(iterator.call(context, obj[i], i, obj) === false) { return; } } // objects } else { for(i in obj) { if(obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj) === false) { return; } } } }, /** * find if a string contains the string using indexOf * @method inStr * @param {String} src * @param {String} find * @return {Boolean} found */ inStr: function inStr(src, find) { return src.indexOf(find) > -1; }, /** * find if a array contains the object using indexOf or a simple polyfill * @method inArray * @param {String} src * @param {String} find * @return {Boolean|Number} false when not found, or the index */ inArray: function inArray(src, find) { if(src.indexOf) { var index = src.indexOf(find); return (index === -1) ? false : index; } else { for(var i = 0, len = src.length; i < len; i++) { if(src[i] === find) { return i; } } return false; } }, /** * convert an array-like object (`arguments`, `touchlist`) to an array * @method toArray * @param {Object} obj * @return {Array} */ toArray: function toArray(obj) { return Array.prototype.slice.call(obj, 0); }, /** * find if a node is in the given parent * @method hasParent * @param {HTMLElement} node * @param {HTMLElement} parent * @return {Boolean} found */ hasParent: function hasParent(node, parent) { while(node) { if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @method getCenter * @param {Array} touches * @return {Object} center contains `pageX`, `pageY`, `clientX` and `clientY` properties */ getCenter: function getCenter(touches) { var pageX = [], pageY = [], clientX = [], clientY = [], min = Math.min, max = Math.max; // no need to loop when only one touch if(touches.length === 1) { return { pageX: touches[0].pageX, pageY: touches[0].pageY, clientX: touches[0].clientX, clientY: touches[0].clientY }; } Utils.each(touches, function(touch) { pageX.push(touch.pageX); pageY.push(touch.pageY); clientX.push(touch.clientX); clientY.push(touch.clientY); }); return { pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2, pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2, clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2, clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2 }; }, /** * calculate the velocity between two points. unit is in px per ms. * @method getVelocity * @param {Number} deltaTime * @param {Number} deltaX * @param {Number} deltaY * @return {Object} velocity `x` and `y` */ getVelocity: function getVelocity(deltaTime, deltaX, deltaY) { return { x: Math.abs(deltaX / deltaTime) || 0, y: Math.abs(deltaY / deltaTime) || 0 }; }, /** * calculate the angle between two coordinates * @method getAngle * @param {Touch} touch1 * @param {Touch} touch2 * @return {Number} angle */ getAngle: function getAngle(touch1, touch2) { var x = touch2.clientX - touch1.clientX, y = touch2.clientY - touch1.clientY; return Math.atan2(y, x) * 180 / Math.PI; }, /** * do a small comparision to get the direction between two touches. * @method getDirection * @param {Touch} touch1 * @param {Touch} touch2 * @return {String} direction matches `DIRECTION_LEFT|RIGHT|UP|DOWN` */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.clientX - touch2.clientX), y = Math.abs(touch1.clientY - touch2.clientY); if(x >= y) { return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN; }, /** * calculate the distance between two touches * @method getDistance * @param {Touch}touch1 * @param {Touch} touch2 * @return {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.clientX - touch1.clientX, y = touch2.clientY - touch1.clientY; return Math.sqrt((x * x) + (y * y)); }, /** * calculate the scale factor between two touchLists * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @method getScale * @param {Array} start array of touches * @param {Array} end array of touches * @return {Number} scale */ getScale: function getScale(start, end) { // need two fingers... if(start.length >= 2 && end.length >= 2) { return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]); } return 1; }, /** * calculate the rotation degrees between two touchLists * @method getRotation * @param {Array} start array of touches * @param {Array} end array of touches * @return {Number} rotation */ getRotation: function getRotation(start, end) { // need two fingers if(start.length >= 2 && end.length >= 2) { return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]); } return 0; }, /** * find out if the direction is vertical * * @method isVertical * @param {String} direction matches `DIRECTION_UP|DOWN` * @return {Boolean} is_vertical */ isVertical: function isVertical(direction) { return direction == DIRECTION_UP || direction == DIRECTION_DOWN; }, /** * set css properties with their prefixes * @param {HTMLElement} element * @param {String} prop * @param {String} value * @param {Boolean} [toggle=true] * @return {Boolean} */ setPrefixedCss: function setPrefixedCss(element, prop, value, toggle) { var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms']; prop = Utils.toCamelCase(prop); for(var i = 0; i < prefixes.length; i++) { var p = prop; // prefixes if(prefixes[i]) { p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1); } // test the style if(p in element.style) { element.style[p] = (toggle == null || toggle) && value || ''; break; } } }, /** * toggle browser default behavior by setting css properties. * `userSelect='none'` also sets `element.onselectstart` to false * `userDrag='none'` also sets `element.ondragstart` to false * * @method toggleBehavior * @param {HtmlElement} element * @param {Object} props * @param {Boolean} [toggle=true] */ toggleBehavior: function toggleBehavior(element, props, toggle) { if(!props || !element || !element.style) { return; } // set the css properties Utils.each(props, function(value, prop) { Utils.setPrefixedCss(element, prop, value, toggle); }); var falseFn = toggle && function() { return false; }; // also the disable onselectstart if(props.userSelect == 'none') { element.onselectstart = falseFn; } // and disable ondragstart if(props.userDrag == 'none') { element.ondragstart = falseFn; } }, /** * convert a string with underscores to camelCase * so prevent_default becomes preventDefault * @param {String} str * @return {String} camelCaseStr */ toCamelCase: function toCamelCase(str) { return str.replace(/[_-]([a-z])/g, function(s) { return s[1].toUpperCase(); }); } }; /** * @module hammer */ /** * @class Event * @static */ var Event = Hammer.event = { /** * when touch events have been fired, this is true * this is used to stop mouse events * @property prevent_mouseevents * @private * @type {Boolean} */ preventMouseEvents: false, /** * if EVENT_START has been fired * @property started * @private * @type {Boolean} */ started: false, /** * when the mouse is hold down, this is true * @property should_detect * @private * @type {Boolean} */ shouldDetect: false, /** * simple event binder with a hook and support for multiple types * @method on * @param {HTMLElement} element * @param {String} type * @param {Function} handler * @param {Function} [hook] * @param {Object} hook.type */ on: function on(element, type, handler, hook) { var types = type.split(' '); Utils.each(types, function(type) { Utils.on(element, type, handler); hook && hook(type); }); }, /** * simple event unbinder with a hook and support for multiple types * @method off * @param {HTMLElement} element * @param {String} type * @param {Function} handler * @param {Function} [hook] * @param {Object} hook.type */ off: function off(element, type, handler, hook) { var types = type.split(' '); Utils.each(types, function(type) { Utils.off(element, type, handler); hook && hook(type); }); }, /** * the core touch event handler. * this finds out if we should to detect gestures * @method onTouch * @param {HTMLElement} element * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Function} handler * @return onTouchHandler {Function} the core event handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; var onTouchHandler = function onTouchHandler(ev) { var srcType = ev.type.toLowerCase(), isPointer = Hammer.HAS_POINTEREVENTS, isMouse = Utils.inStr(srcType, 'mouse'), triggerType; // if we are in a mouseevent, but there has been a touchevent triggered in this session // we want to do nothing. simply break out of the event. if(isMouse && self.preventMouseEvents) { return; // mousebutton must be down } else if(isMouse && eventType == EVENT_START && ev.button === 0) { self.preventMouseEvents = false; self.shouldDetect = true; } else if(isPointer && eventType == EVENT_START) { self.shouldDetect = (ev.buttons === 1 || PointerEvent.matchType(POINTER_TOUCH, ev)); // just a valid start event, but no mouse } else if(!isMouse && eventType == EVENT_START) { self.preventMouseEvents = true; self.shouldDetect = true; } // update the pointer event before entering the detection if(isPointer && eventType != EVENT_END) { PointerEvent.updatePointer(eventType, ev); } // we are in a touch/down state, so allowed detection of gestures if(self.shouldDetect) { triggerType = self.doDetect.call(self, ev, eventType, element, handler); } // ...and we are done with the detection // so reset everything to start each detection totally fresh if(triggerType == EVENT_END) { self.preventMouseEvents = false; self.shouldDetect = false; PointerEvent.reset(); // update the pointerevent object after the detection } if(isPointer && eventType == EVENT_END) { PointerEvent.updatePointer(eventType, ev); } }; this.on(element, EVENT_TYPES[eventType], onTouchHandler); return onTouchHandler; }, /** * the core detection method * this finds out what hammer-touch-events to trigger * @method doDetect * @param {Object} ev * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {HTMLElement} element * @param {Function} handler * @return {String} triggerType matches `EVENT_START|MOVE|END` */ doDetect: function doDetect(ev, eventType, element, handler) { var touchList = this.getTouchList(ev, eventType); var touchListLength = touchList.length; var triggerType = eventType; var triggerChange = touchList.trigger; // used by fakeMultitouch plugin var changedLength = touchListLength; // at each touchstart-like event we want also want to trigger a TOUCH event... if(eventType == EVENT_START) { triggerChange = EVENT_TOUCH; // ...the same for a touchend-like event } else if(eventType == EVENT_END) { triggerChange = EVENT_RELEASE; // keep track of how many touches have been removed changedLength = touchList.length - ((ev.changedTouches) ? ev.changedTouches.length : 1); } // after there are still touches on the screen, // we just want to trigger a MOVE event. so change the START or END to a MOVE // but only after detection has been started, the first time we actualy want a START if(changedLength > 0 && this.started) { triggerType = EVENT_MOVE; } // detection has been started, we keep track of this, see above this.started = true; // generate some event data, some basic information var evData = this.collectEventData(element, triggerType, touchList, ev); // trigger the triggerType event before the change (TOUCH, RELEASE) events // but the END event should be at last if(eventType != EVENT_END) { handler.call(Detection, evData); } // trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed if(triggerChange) { evData.changedLength = changedLength; evData.eventType = triggerChange; handler.call(Detection, evData); evData.eventType = triggerType; delete evData.changedLength; } // trigger the END event if(triggerType == EVENT_END) { handler.call(Detection, evData); // ...and we are done with the detection // so reset everything to start each detection totally fresh this.started = false; } return triggerType; }, /** * we have different events for each device/browser * determine what we need and set them in the EVENT_TYPES constant * the `onTouch` method is bind to these properties. * @method determineEventTypes * @return {Object} events */ determineEventTypes: function determineEventTypes() { var types; if(Hammer.HAS_POINTEREVENTS) { if(window.PointerEvent) { types = [ 'pointerdown', 'pointermove', 'pointerup pointercancel lostpointercapture' ]; } else { types = [ 'MSPointerDown', 'MSPointerMove', 'MSPointerUp MSPointerCancel MSLostPointerCapture' ]; } } else if(Hammer.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel' ]; } else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup' ]; } EVENT_TYPES[EVENT_START] = types[0]; EVENT_TYPES[EVENT_MOVE] = types[1]; EVENT_TYPES[EVENT_END] = types[2]; return EVENT_TYPES; }, /** * create touchList depending on the event * @method getTouchList * @param {Object} ev * @param {String} eventType * @return {Array} touches */ getTouchList: function getTouchList(ev, eventType) { // get the fake pointerEvent touchlist if(Hammer.HAS_POINTEREVENTS) { return PointerEvent.getTouchList(); } // get the touchlist if(ev.touches) { if(eventType == EVENT_MOVE) { return ev.touches; } var identifiers = []; var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches)); var touchList = []; Utils.each(concat, function(touch) { if(Utils.inArray(identifiers, touch.identifier) === false) { touchList.push(touch); } identifiers.push(touch.identifier); }); return touchList; } // make fake touchList from mouse position ev.identifier = 1; return [ev]; }, /** * collect basic event data * @method collectEventData * @param {HTMLElement} element * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Array} touches * @param {Object} ev * @return {Object} ev */ collectEventData: function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = POINTER_TOUCH; if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) { pointerType = POINTER_MOUSE; } else if(PointerEvent.matchType(POINTER_PEN, ev)) { pointerType = POINTER_PEN; } return { center: Utils.getCenter(touches), timeStamp: Date.now(), target: ev.target, touches: touches, eventType: eventType, pointerType: pointerType, srcEvent: ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { var srcEvent = this.srcEvent; srcEvent.preventManipulation && srcEvent.preventManipulation(); srcEvent.preventDefault && srcEvent.preventDefault(); }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return Detection.stopDetect(); } }; } }; /** * @module hammer * * @class PointerEvent * @static */ var PointerEvent = Hammer.PointerEvent = { /** * holds all pointers, by `identifier` * @property pointers * @type {Object} */ pointers: {}, /** * get the pointers as an array * @method getTouchList * @return {Array} touchlist */ getTouchList: function getTouchList() { var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Utils.each(this.pointers, function(pointer) { touchlist.push(pointer); }); return touchlist; }, /** * update the position of a pointer * @method updatePointer * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Object} pointerEvent */ updatePointer: function updatePointer(eventType, pointerEvent) { if(eventType == EVENT_END || (eventType != EVENT_END && pointerEvent.buttons !== 1)) { delete this.pointers[pointerEvent.pointerId]; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } }, /** * check if ev matches pointertype * @method matchType * @param {String} pointerType matches `POINTER_MOUSE|TOUCH|PEN` * @param {PointerEvent} ev */ matchType: function matchType(pointerType, ev) { if(!ev.pointerType) { return false; } var pt = ev.pointerType, types = {}; types[POINTER_MOUSE] = (pt === (ev.MSPOINTER_TYPE_MOUSE || POINTER_MOUSE)); types[POINTER_TOUCH] = (pt === (ev.MSPOINTER_TYPE_TOUCH || POINTER_TOUCH)); types[POINTER_PEN] = (pt === (ev.MSPOINTER_TYPE_PEN || POINTER_PEN)); return types[pointerType]; }, /** * reset the stored pointers * @method reset */ reset: function resetList() { this.pointers = {}; } }; /** * @module hammer * * @class Detection * @static */ var Detection = Hammer.detection = { // contains all registred Hammer.gestures in the correct order gestures: [], // data of the current Hammer.gesture detection session current: null, // the previous Hammer.gesture session data // is a full clone of the previous gesture.current object previous: null, // when this becomes true, no gestures are fired stopped: false, /** * start Hammer.gesture detection * @method startDetect * @param {Hammer.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a Hammer.gesture detection on an element if(this.current) { return; } this.stopped = false; // holds current session this.current = { inst: inst, // reference to HammerInstance we're working for startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent: false, // last eventData lastCalcEvent: false, // last eventData for calculations. futureCalcEvent: false, // last eventData for calculations. lastCalcData: {}, // last lastCalcData name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * Hammer.gesture detection * @method detect * @param {Object} eventData * @return {any} */ detect: function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // hammer instance and instance options var inst = this.current.inst, instOptions = inst.options; // call Hammer.gesture handlers Utils.each(this.gestures, function triggerGesture(gesture) { // only when the instance options have enabled this gesture if(!this.stopped && inst.enabled && instOptions[gesture.name]) { gesture.handler.call(gesture, eventData, inst); } }, this); // store as previous event event if(this.current) { this.current.lastEvent = eventData; } if(eventData.eventType == EVENT_END) { this.stopDetect(); } return eventData; }, /** * clear the Hammer.gesture vars * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected * to stop other Hammer.gestures from being fired * @method stopDetect */ stopDetect: function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = Utils.extend({}, this.current); // reset the current this.current = null; this.stopped = true; }, /** * calculate velocity, angle and direction * @method getVelocityData * @param {Object} ev * @param {Object} center * @param {Number} deltaTime * @param {Number} deltaX * @param {Number} deltaY */ getCalculatedData: function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) { var cur = this.current, recalc = false, calcEv = cur.lastCalcEvent, calcData = cur.lastCalcData; if(calcEv && ev.timeStamp - calcEv.timeStamp > Hammer.CALCULATE_INTERVAL) { center = calcEv.center; deltaTime = ev.timeStamp - calcEv.timeStamp; deltaX = ev.center.clientX - calcEv.center.clientX; deltaY = ev.center.clientY - calcEv.center.clientY; recalc = true; } if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) { cur.futureCalcEvent = ev; } if(!cur.lastCalcEvent || recalc) { calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY); calcData.angle = Utils.getAngle(center, ev.center); calcData.direction = Utils.getDirection(center, ev.center); cur.lastCalcEvent = cur.futureCalcEvent || ev; cur.futureCalcEvent = ev; } ev.velocityX = calcData.velocity.x; ev.velocityY = calcData.velocity.y; ev.interimAngle = calcData.angle; ev.interimDirection = calcData.direction; }, /** * extend eventData for Hammer.gestures * @method extendEventData * @param {Object} ev * @return {Object} ev */ extendEventData: function extendEventData(ev) { var cur = this.current, startEv = cur.startEvent, lastEv = cur.lastEvent || startEv; // update the start touchlist to calculate the scale/rotation if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) { startEv.touches = []; Utils.each(ev.touches, function(touch) { startEv.touches.push({ clientX: touch.clientX, clientY: touch.clientY }); }); } var deltaTime = ev.timeStamp - startEv.timeStamp, deltaX = ev.center.clientX - startEv.center.clientX, deltaY = ev.center.clientY - startEv.center.clientY; this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY); Utils.extend(ev, { startEvent: startEv, deltaTime: deltaTime, deltaX: deltaX, deltaY: deltaY, distance: Utils.getDistance(startEv.center, ev.center), angle: Utils.getAngle(startEv.center, ev.center), direction: Utils.getDirection(startEv.center, ev.center), scale: Utils.getScale(startEv.touches, ev.touches), rotation: Utils.getRotation(startEv.touches, ev.touches) }); return ev; }, /** * register new gesture * @method register * @param {Object} gesture object, see `gestures/` for documentation * @return {Array} gestures */ register: function register(gesture) { // add an enable gesture options if there is no given var options = gesture.defaults || {}; if(options[gesture.name] === undefined) { options[gesture.name] = true; } // extend Hammer default options with the Hammer.gesture options Utils.extend(Hammer.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add Hammer.gesture to the list this.gestures.push(gesture); // sort the list by index this.gestures.sort(function(a, b) { if(a.index < b.index) { return -1; } if(a.index > b.index) { return 1; } return 0; }); return this.gestures; } }; /** * @module hammer */ /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * * @class Instance * @constructor * @param {HTMLElement} element * @param {Object} [options={}] options are merged with `Hammer.defaults` * @return {Hammer.Instance} */ Hammer.Instance = function(element, options) { var self = this; // setup HammerJS window events and register all gestures // this also sets up the default options setup(); /** * @property element * @type {HTMLElement} */ this.element = element; /** * @property enabled * @type {Boolean} * @protected */ this.enabled = true; /** * options, merged with the defaults * options with an _ are converted to camelCase * @property options * @type {Object} */ Utils.each(options, function(value, name) { delete options[name]; options[Utils.toCamelCase(name)] = value; }); this.options = Utils.extend(Utils.extend({}, Hammer.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.behavior) { Utils.toggleBehavior(this.element, this.options.behavior, true); } /** * event start handler on the element to start the detection * @property eventStartHandler * @type {Object} */ this.eventStartHandler = Event.onTouch(element, EVENT_START, function(ev) { if(self.enabled && ev.eventType == EVENT_START) { Detection.startDetect(self, ev); } else if(ev.eventType == EVENT_TOUCH) { Detection.detect(ev); } }); /** * keep a list of user event handlers which needs to be removed when calling 'dispose' * @property eventHandlers * @type {Array} */ this.eventHandlers = []; }; Hammer.Instance.prototype = { /** * bind events to the instance * @method on * @chainable * @param {String} gestures multiple gestures by splitting with a space * @param {Function} handler * @param {Object} handler.ev event object */ on: function onEvent(gestures, handler) { var self = this; Event.on(self.element, gestures, handler, function(type) { self.eventHandlers.push({ gesture: type, handler: handler }); }); return self; }, /** * unbind events to the instance * @method off * @chainable * @param {String} gestures * @param {Function} handler */ off: function offEvent(gestures, handler) { var self = this; Event.off(self.element, gestures, handler, function(type) { var index = Utils.inArray({ gesture: type, handler: handler }); if(index !== false) { self.eventHandlers.splice(index, 1); } }); return self; }, /** * trigger gesture event * @method trigger * @chainable * @param {String} gesture * @param {Object} [eventData] */ trigger: function triggerEvent(gesture, eventData) { // optional if(!eventData) { eventData = {}; } // create DOM event var event = Hammer.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(Utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @method enable * @chainable * @param {Boolean} state */ enable: function enable(state) { this.enabled = state; return this; }, /** * dispose this hammer instance * @method dispose * @return {Null} */ dispose: function dispose() { var i, eh; // undo all changes made by stop_browser_behavior Utils.toggleBehavior(this.element, this.options.behavior, false); // unbind all custom event handlers for(i = -1; (eh = this.eventHandlers[++i]);) { Utils.off(this.element, eh.gesture, eh.handler); } this.eventHandlers = []; // unbind the start event listener Event.off(this.element, EVENT_TYPES[EVENT_START], this.eventStartHandler); return null; } }; /** * @module gestures */ /** * Move with x fingers (default 1) around on the page. * Preventing the default browser behavior is a good way to improve feel and working. * ```` * hammertime.on("drag", function(ev) { * console.log(ev); * ev.gesture.preventDefault(); * }); * ```` * * @class Drag * @static */ /** * @event drag * @param {Object} ev */ /** * @event dragstart * @param {Object} ev */ /** * @event dragend * @param {Object} ev */ /** * @event drapleft * @param {Object} ev */ /** * @event dragright * @param {Object} ev */ /** * @event dragup * @param {Object} ev */ /** * @event dragdown * @param {Object} ev */ /** * @param {String} name */ (function(name) { var triggered = false; function dragGesture(ev, inst) { var cur = Detection.current; // max touches if(inst.options.dragMaxTouches > 0 && ev.touches.length > inst.options.dragMaxTouches) { return; } switch(ev.eventType) { case EVENT_START: triggered = false; break; case EVENT_MOVE: // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.distance < inst.options.dragMinDistance && cur.name != name) { return; } var startCenter = cur.startEvent.center; // we are dragging! if(cur.name != name) { cur.name = name; if(inst.options.dragDistanceCorrection && ev.distance > 0) { // When a drag is triggered, set the event center to dragMinDistance pixels from the original event center. // Without this correction, the dragged distance would jumpstart at dragMinDistance pixels instead of at 0. // It might be useful to save the original start point somewhere var factor = Math.abs(inst.options.dragMinDistance / ev.distance); startCenter.pageX += ev.deltaX * factor; startCenter.pageY += ev.deltaY * factor; startCenter.clientX += ev.deltaX * factor; startCenter.clientY += ev.deltaY * factor; // recalculate event data using new start point ev = Detection.extendEventData(ev); } } // lock drag to axis? if(cur.lastEvent.dragLockToAxis || ( inst.options.dragLockToAxis && inst.options.dragLockMinDistance <= ev.distance )) { ev.dragLockToAxis = true; } // keep direction on the axis that the drag gesture started on var lastDirection = cur.lastEvent.direction; if(ev.dragLockToAxis && lastDirection !== ev.direction) { if(Utils.isVertical(lastDirection)) { ev.direction = (ev.deltaY < 0) ? DIRECTION_UP : DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!triggered) { inst.trigger(name + 'start', ev); triggered = true; } // trigger events inst.trigger(name, ev); inst.trigger(name + ev.direction, ev); var isVertical = Utils.isVertical(ev.direction); // block the browser events if((inst.options.dragBlockVertical && isVertical) || (inst.options.dragBlockHorizontal && !isVertical)) { ev.preventDefault(); } break; case EVENT_RELEASE: if(triggered && ev.changedLength <= inst.options.dragMaxTouches) { inst.trigger(name + 'end', ev); triggered = false; } break; case EVENT_END: triggered = false; break; } } Hammer.gestures.Drag = { name: name, index: 50, handler: dragGesture, defaults: { /** * minimal movement that have to be made before the drag event gets triggered * @property dragMinDistance * @type {Number} * @default 10 */ dragMinDistance: 10, /** * Set dragDistanceCorrection to true to make the starting point of the drag * be calculated from where the drag was triggered, not from where the touch started. * Useful to avoid a jerk-starting drag, which can make fine-adjustments * through dragging difficult, and be visually unappealing. * @property dragDistanceCorrection * @type {Boolean} * @default true */ dragDistanceCorrection: true, /** * set 0 for unlimited, but this can conflict with transform * @property dragMaxTouches * @type {Number} * @default 1 */ dragMaxTouches: 1, /** * prevent default browser behavior when dragging occurs * be careful with it, it makes the element a blocking element * when you are using the drag gesture, it is a good practice to set this true * @property dragBlockHorizontal * @type {Boolean} * @default false */ dragBlockHorizontal: false, /** * same as `dragBlockHorizontal`, but for vertical movement * @property dragBlockVertical * @type {Boolean} * @default false */ dragBlockVertical: false, /** * dragLockToAxis keeps the drag gesture on the axis that it started on, * It disallows vertical directions if the initial direction was horizontal, and vice versa. * @property dragLockToAxis * @type {Boolean} * @default false */ dragLockToAxis: false, /** * drag lock only kicks in when distance > dragLockMinDistance * This way, locking occurs only when the distance has become large enough to reliably determine the direction * @property dragLockMinDistance * @type {Number} * @default 25 */ dragLockMinDistance: 25 } }; })('drag'); /** * @module gestures */ /** * trigger a simple gesture event, so you can do anything in your handler. * only usable if you know what your doing... * * @class Gesture * @static */ /** * @event gesture * @param {Object} ev */ Hammer.gestures.Gesture = { name: 'gesture', index: 1337, handler: function releaseGesture(ev, inst) { inst.trigger(this.name, ev); } }; /** * @module gestures */ /** * Touch stays at the same place for x time * * @class Hold * @static */ /** * @event hold * @param {Object} ev */ /** * @param {String} name */ (function(name) { var timer; function holdGesture(ev, inst) { var options = inst.options, current = Detection.current; switch(ev.eventType) { case EVENT_START: clearTimeout(timer); // set the gesture so we can check in the timeout if it still is current.name = name; // set timer and if after the timeout it still is hold, // we trigger the hold event timer = setTimeout(function() { if(current && current.name == name) { inst.trigger(name, ev); } }, options.holdTimeout); break; case EVENT_MOVE: if(ev.distance > options.holdThreshold) { clearTimeout(timer); } break; case EVENT_RELEASE: clearTimeout(timer); break; } } Hammer.gestures.Hold = { name: name, index: 10, defaults: { /** * @property holdTimeout * @type {Number} * @default 500 */ holdTimeout: 500, /** * movement allowed while holding * @property holdThreshold * @type {Number} * @default 2 */ holdThreshold: 2 }, handler: holdGesture }; })('hold'); /** * @module gestures */ /** * when a touch is being released from the page * * @class Release * @static */ /** * @event release * @param {Object} ev */ Hammer.gestures.Release = { name: 'release', index: Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == EVENT_RELEASE) { inst.trigger(this.name, ev); } } }; /** * @module gestures */ /** * triggers swipe events when the end velocity is above the threshold * for best usage, set `preventDefault` (on the drag gesture) to `true` * ```` * hammertime.on("dragleft swipeleft", function(ev) { * console.log(ev); * ev.gesture.preventDefault(); * }); * ```` * * @class Swipe * @static */ /** * @event swipe * @param {Object} ev */ /** * @event swipeleft * @param {Object} ev */ /** * @event swiperight * @param {Object} ev */ /** * @event swipeup * @param {Object} ev */ /** * @event swipedown * @param {Object} ev */ Hammer.gestures.Swipe = { name: 'swipe', index: 40, defaults: { /** * @property swipeMinTouches * @type {Number} * @default 1 */ swipeMinTouches: 1, /** * @property swipeMaxTouches * @type {Number} * @default 1 */ swipeMaxTouches: 1, /** * horizontal swipe velocity * @property swipeVelocityX * @type {Number} * @default 0.6 */ swipeVelocityX: 0.6, /** * vertical swipe velocity * @property swipeVelocityY * @type {Number} * @default 0.6 */ swipeVelocityY: 0.6 }, handler: function swipeGesture(ev, inst) { if(ev.eventType == EVENT_RELEASE) { var touches = ev.touches.length, options = inst.options; // max touches if(touches < options.swipeMinTouches || touches > options.swipeMaxTouches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > options.swipeVelocityX || ev.velocityY > options.swipeVelocityY) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * @module gestures */ /** * Single tap and a double tap on a place * * @class Tap * @static */ /** * @event tap * @param {Object} ev */ /** * @event doubletap * @param {Object} ev */ /** * @param {String} name */ (function(name) { var hasMoved = false; function tapGesture(ev, inst) { var options = inst.options, current = Detection.current, prev = Detection.previous, sincePrev, didDoubleTap; switch(ev.eventType) { case EVENT_START: hasMoved = false; break; case EVENT_MOVE: hasMoved = hasMoved || (ev.distance > options.tapMaxDistance); break; case EVENT_END: if(!Utils.inStr(ev.srcEvent.type, 'cancel') && ev.deltaTime < options.tapMaxTime && !hasMoved) { // previous gesture, for the double tap since these are two different gesture detections sincePrev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp; didDoubleTap = false; // check if double tap if(prev && prev.name == name && (sincePrev && sincePrev < options.doubleTapInterval) && ev.distance < options.doubleTapDistance) { inst.trigger('doubletap', ev); didDoubleTap = true; } // do a single tap if(!didDoubleTap || options.tapAlways) { current.name = name; inst.trigger(current.name, ev); } } break; } } Hammer.gestures.Tap = { name: name, index: 100, handler: tapGesture, defaults: { /** * max time of a tap, this is for the slow tappers * @property tapMaxTime * @type {Number} * @default 250 */ tapMaxTime: 250, /** * max distance of movement of a tap, this is for the slow tappers * @property tapMaxDistance * @type {Number} * @default 10 */ tapMaxDistance: 10, /** * always trigger the `tap` event, even while double-tapping * @property tapAlways * @type {Boolean} * @default true */ tapAlways: true, /** * max distance between two taps * @property doubleTapDistance * @type {Number} * @default 20 */ doubleTapDistance: 20, /** * max time between two taps * @property doubleTapInterval * @type {Number} * @default 300 */ doubleTapInterval: 300 } }; })('tap'); /** * @module gestures */ /** * when a touch is being touched at the page * * @class Touch * @static */ /** * @event touch * @param {Object} ev */ Hammer.gestures.Touch = { name: 'touch', index: -Infinity, defaults: { /** * call preventDefault at touchstart, and makes the element blocking by disabling the scrolling of the page, * but it improves gestures like transforming and dragging. * be careful with using this, it can be very annoying for users to be stuck on the page * @property preventDefault * @type {Boolean} * @default false */ preventDefault: false, /** * disable mouse events, so only touch (or pen!) input triggers events * @property preventMouse * @type {Boolean} * @default false */ preventMouse: false }, handler: function touchGesture(ev, inst) { if(inst.options.preventMouse && ev.pointerType == POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.preventDefault) { ev.preventDefault(); } if(ev.eventType == EVENT_TOUCH) { inst.trigger('touch', ev); } } }; /** * @module gestures */ /** * User want to scale or rotate with 2 fingers * Preventing the default browser behavior is a good way to improve feel and working. This can be done with the * `preventDefault` option. * * @class Transform * @static */ /** * @event transform * @param {Object} ev */ /** * @event transformstart * @param {Object} ev */ /** * @event transformend * @param {Object} ev */ /** * @event pinchin * @param {Object} ev */ /** * @event pinchout * @param {Object} ev */ /** * @event rotate * @param {Object} ev */ /** * @param {String} name */ (function(name) { var triggered = false; function transformGesture(ev, inst) { switch(ev.eventType) { case EVENT_START: triggered = false; break; case EVENT_MOVE: // at least multitouch if(ev.touches.length < 2) { return; } var scaleThreshold = Math.abs(1 - ev.scale); var rotationThreshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scaleThreshold < inst.options.transformMinScale && rotationThreshold < inst.options.transformMinRotation) { return; } // we are transforming! Detection.current.name = name; // first time, trigger dragstart event if(!triggered) { inst.trigger(name + 'start', ev); triggered = true; } inst.trigger(name, ev); // basic transform event // trigger rotate event if(rotationThreshold > inst.options.transformMinRotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scaleThreshold > inst.options.transformMinScale) { inst.trigger('pinch', ev); inst.trigger('pinch' + (ev.scale < 1 ? 'in' : 'out'), ev); } break; case EVENT_RELEASE: if(triggered && ev.changedLength < 2) { inst.trigger(name + 'end', ev); triggered = false; } break; } } Hammer.gestures.Transform = { name: name, index: 45, defaults: { /** * minimal scale factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 * @property transformMinScale * @type {Number} * @default 0.01 */ transformMinScale: 0.01, /** * rotation in degrees * @property transformMinRotation * @type {Number} * @default 1 */ transformMinRotation: 1 }, handler: transformGesture }; })('transform'); /** * @module hammer */ // AMD export if(typeof define == 'function' && define.amd) { define(function() { return Hammer; }); // commonjs export } else if(typeof module !== 'undefined' && module.exports) { module.exports = Hammer; // browser export } else { window.Hammer = Hammer; } })(window); /*! iScroll v5.0.6 ~ (c) 2008-2013 Matteo Spinelli ~ http://cubiq.org/license */ var IScroll = (function (window, document, Math) { var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; var utils = (function () { var me = {}; var _elementStyle = document.createElement('div').style; var _vendor = (function () { var vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'], transform, i = 0, l = vendors.length; for ( ; i < l; i++ ) { transform = vendors[i] + 'ransform'; if ( transform in _elementStyle ) return vendors[i].substr(0, vendors[i].length-1); } return false; })(); function _prefixStyle (style) { if ( _vendor === false ) return false; if ( _vendor === '' ) return style; return _vendor + style.charAt(0).toUpperCase() + style.substr(1); } me.getTime = Date.now || function getTime () { return new Date().getTime(); }; me.extend = function (target, obj) { for ( var i in obj ) { target[i] = obj[i]; } }; me.addEvent = function (el, type, fn, capture) { el.addEventListener(type, fn, !!capture); }; me.removeEvent = function (el, type, fn, capture) { el.removeEventListener(type, fn, !!capture); }; me.momentum = function (current, start, time, lowerMargin, wrapperSize) { var distance = current - start, speed = Math.abs(distance) / time, destination, duration, deceleration = 0.0006; destination = current + ( speed * speed ) / ( 2 * deceleration ) * ( distance < 0 ? -1 : 1 ); duration = speed / deceleration; if ( destination < lowerMargin ) { destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin; distance = Math.abs(destination - current); duration = distance / speed; } else if ( destination > 0 ) { destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0; distance = Math.abs(current) + destination; duration = distance / speed; } return { destination: Math.round(destination), duration: duration }; }; var _transform = _prefixStyle('transform'); me.extend(me, { hasTransform: _transform !== false, hasPerspective: _prefixStyle('perspective') in _elementStyle, hasTouch: 'ontouchstart' in window, hasPointer: navigator.msPointerEnabled, hasTransition: _prefixStyle('transition') in _elementStyle }); me.isAndroidBrowser = /Android/.test(window.navigator.appVersion) && /Version\/\d/.test(window.navigator.appVersion); me.extend(me.style = {}, { transform: _transform, transitionTimingFunction: _prefixStyle('transitionTimingFunction'), transitionDuration: _prefixStyle('transitionDuration'), transformOrigin: _prefixStyle('transformOrigin') }); me.hasClass = function (e, c) { var re = new RegExp("(^|\\s)" + c + "(\\s|$)"); return re.test(e.className); }; me.addClass = function (e, c) { if ( me.hasClass(e, c) ) { return; } var newclass = e.className.split(' '); newclass.push(c); e.className = newclass.join(' '); }; me.removeClass = function (e, c) { if ( !me.hasClass(e, c) ) { return; } var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g'); e.className = e.className.replace(re, ' '); }; me.offset = function (el) { var left = -el.offsetLeft, top = -el.offsetTop; // jshint -W084 while (el = el.offsetParent) { left -= el.offsetLeft; top -= el.offsetTop; } // jshint +W084 return { left: left, top: top }; }; me.preventDefaultException = function (el, exceptions) { for ( var i in exceptions ) { if ( exceptions[i].test(el[i]) ) { return true; } } return false; }; me.extend(me.eventType = {}, { touchstart: 1, touchmove: 1, touchend: 1, mousedown: 2, mousemove: 2, mouseup: 2, MSPointerDown: 3, MSPointerMove: 3, MSPointerUp: 3 }); me.extend(me.ease = {}, { quadratic: { style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)', fn: function (k) { return k * ( 2 - k ); } }, circular: { style: 'cubic-bezier(0.1, 0.57, 0.1, 1)', // Not properly "circular" but this looks better, it should be (0.075, 0.82, 0.165, 1) fn: function (k) { return Math.sqrt( 1 - ( --k * k ) ); } }, back: { style: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)', fn: function (k) { var b = 4; return ( k = k - 1 ) * k * ( ( b + 1 ) * k + b ) + 1; } }, bounce: { style: '', fn: function (k) { if ( ( k /= 1 ) < ( 1 / 2.75 ) ) { return 7.5625 * k * k; } else if ( k < ( 2 / 2.75 ) ) { return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; } else if ( k < ( 2.5 / 2.75 ) ) { return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; } else { return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; } } }, elastic: { style: '', fn: function (k) { var f = 0.22, e = 0.4; if ( k === 0 ) { return 0; } if ( k == 1 ) { return 1; } return ( e * Math.pow( 2, - 10 * k ) * Math.sin( ( k - f / 4 ) * ( 2 * Math.PI ) / f ) + 1 ); } } }); me.tap = function (e, eventName) { var ev = document.createEvent('Event'); ev.initEvent(eventName, true, true); ev.pageX = e.pageX; ev.pageY = e.pageY; e.target.dispatchEvent(ev); }; me.click = function (e) { var target = e.target, ev; if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') { ev = document.createEvent('MouseEvents'); ev.initMouseEvent('click', true, true, e.view, 1, target.screenX, target.screenY, target.clientX, target.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, 0, null); ev._constructed = true; target.dispatchEvent(ev); } }; return me; })(); function IScroll (el, options) { this.wrapper = typeof el == 'string' ? document.querySelector(el) : el; this.scroller = this.wrapper.children[0]; this.scrollerStyle = this.scroller.style; // cache style for better performance this.options = { // INSERT POINT: OPTIONS startX: 0, startY: 0, scrollY: true, directionLockThreshold: 5, momentum: true, bounce: true, bounceTime: 600, bounceEasing: '', preventDefault: true, preventDefaultException: { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ }, HWCompositing: true, useTransition: true, useTransform: true }; for ( var i in options ) { this.options[i] = options[i]; } // Normalize options this.translateZ = this.options.HWCompositing && utils.hasPerspective ? ' translateZ(0)' : ''; this.options.useTransition = utils.hasTransition && this.options.useTransition; this.options.useTransform = utils.hasTransform && this.options.useTransform; this.options.eventPassthrough = this.options.eventPassthrough === true ? 'vertical' : this.options.eventPassthrough; this.options.preventDefault = !this.options.eventPassthrough && this.options.preventDefault; // If you want eventPassthrough I have to lock one of the axes this.options.scrollY = this.options.eventPassthrough == 'vertical' ? false : this.options.scrollY; this.options.scrollX = this.options.eventPassthrough == 'horizontal' ? false : this.options.scrollX; // With eventPassthrough we also need lockDirection mechanism this.options.freeScroll = this.options.freeScroll && !this.options.eventPassthrough; this.options.directionLockThreshold = this.options.eventPassthrough ? 0 : this.options.directionLockThreshold; this.options.bounceEasing = typeof this.options.bounceEasing == 'string' ? utils.ease[this.options.bounceEasing] || utils.ease.circular : this.options.bounceEasing; this.options.resizePolling = this.options.resizePolling === undefined ? 60 : this.options.resizePolling; if ( this.options.tap === true ) { this.options.tap = 'tap'; } // INSERT POINT: NORMALIZATION // Some defaults this.x = 0; this.y = 0; this.directionX = 0; this.directionY = 0; this._events = {}; // INSERT POINT: DEFAULTS this._init(); this.refresh(); this.scrollTo(this.options.startX, this.options.startY); this.enable(); } IScroll.prototype = { version: '5.0.6', _init: function () { this._initEvents(); // INSERT POINT: _init }, destroy: function () { this._initEvents(true); this._execEvent('destroy'); }, _transitionEnd: function (e) { if ( e.target != this.scroller ) { return; } this._transitionTime(0); if ( !this.resetPosition(this.options.bounceTime) ) { this._execEvent('scrollEnd'); } }, _start: function (e) { // React to left mouse button only if ( utils.eventType[e.type] != 1 ) { if ( e.button !== 0 ) { return; } } if ( !this.enabled || (this.initiated && utils.eventType[e.type] !== this.initiated) ) { return; } if ( this.options.preventDefault && !utils.isAndroidBrowser && !utils.preventDefaultException(e.target, this.options.preventDefaultException) ) { e.preventDefault(); // This seems to break default Android browser } var point = e.touches ? e.touches[0] : e, pos; this.initiated = utils.eventType[e.type]; this.moved = false; this.distX = 0; this.distY = 0; this.directionX = 0; this.directionY = 0; this.directionLocked = 0; this._transitionTime(); this.isAnimating = false; this.startTime = utils.getTime(); if ( this.options.useTransition && this.isInTransition ) { pos = this.getComputedPosition(); this._translate(Math.round(pos.x), Math.round(pos.y)); this._execEvent('scrollEnd'); this.isInTransition = false; } this.startX = this.x; this.startY = this.y; this.absStartX = this.x; this.absStartY = this.y; this.pointX = point.pageX; this.pointY = point.pageY; this._execEvent('beforeScrollStart'); }, _move: function (e) { if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) { return; } if ( this.options.preventDefault ) { // increases performance on Android? TODO: check! e.preventDefault(); } var point = e.touches ? e.touches[0] : e, deltaX = point.pageX - this.pointX, deltaY = point.pageY - this.pointY, timestamp = utils.getTime(), newX, newY, absDistX, absDistY; this.pointX = point.pageX; this.pointY = point.pageY; this.distX += deltaX; this.distY += deltaY; absDistX = Math.abs(this.distX); absDistY = Math.abs(this.distY); // We need to move at least 10 pixels for the scrolling to initiate if ( timestamp - this.endTime > 300 && (absDistX < 10 && absDistY < 10) ) { return; } // If you are scrolling in one direction lock the other if ( !this.directionLocked && !this.options.freeScroll ) { if ( absDistX > absDistY + this.options.directionLockThreshold ) { this.directionLocked = 'h'; // lock horizontally } else if ( absDistY >= absDistX + this.options.directionLockThreshold ) { this.directionLocked = 'v'; // lock vertically } else { this.directionLocked = 'n'; // no lock } } if ( this.directionLocked == 'h' ) { if ( this.options.eventPassthrough == 'vertical' ) { e.preventDefault(); } else if ( this.options.eventPassthrough == 'horizontal' ) { this.initiated = false; return; } deltaY = 0; } else if ( this.directionLocked == 'v' ) { if ( this.options.eventPassthrough == 'horizontal' ) { e.preventDefault(); } else if ( this.options.eventPassthrough == 'vertical' ) { this.initiated = false; return; } deltaX = 0; } deltaX = this.hasHorizontalScroll ? deltaX : 0; deltaY = this.hasVerticalScroll ? deltaY : 0; newX = this.x + deltaX; newY = this.y + deltaY; // Slow down if outside of the boundaries if ( newX > 0 || newX < this.maxScrollX ) { newX = this.options.bounce ? this.x + deltaX / 3 : newX > 0 ? 0 : this.maxScrollX; } if ( newY > 0 || newY < this.maxScrollY ) { newY = this.options.bounce ? this.y + deltaY / 3 : newY > 0 ? 0 : this.maxScrollY; } this.directionX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0; this.directionY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0; if ( !this.moved ) { this._execEvent('scrollStart'); } this.moved = true; this._translate(newX, newY); /* REPLACE START: _move */ if ( timestamp - this.startTime > 300 ) { this.startTime = timestamp; this.startX = this.x; this.startY = this.y; } /* REPLACE END: _move */ }, _end: function (e) { if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) { return; } if ( this.options.preventDefault && !utils.preventDefaultException(e.target, this.options.preventDefaultException) ) { e.preventDefault(); } var point = e.changedTouches ? e.changedTouches[0] : e, momentumX, momentumY, duration = utils.getTime() - this.startTime, newX = Math.round(this.x), newY = Math.round(this.y), distanceX = Math.abs(newX - this.startX), distanceY = Math.abs(newY - this.startY), time = 0, easing = ''; this.scrollTo(newX, newY); // ensures that the last position is rounded this.isInTransition = 0; this.initiated = 0; this.endTime = utils.getTime(); // reset if we are outside of the boundaries if ( this.resetPosition(this.options.bounceTime) ) { return; } // we scrolled less than 10 pixels if ( !this.moved ) { if ( this.options.tap ) { utils.tap(e, this.options.tap); } if ( this.options.click ) { utils.click(e); } return; } if ( this._events.flick && duration < 200 && distanceX < 100 && distanceY < 100 ) { this._execEvent('flick'); return; } // start momentum animation if needed if ( this.options.momentum && duration < 300 ) { momentumX = this.hasHorizontalScroll ? utils.momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0) : { destination: newX, duration: 0 }; momentumY = this.hasVerticalScroll ? utils.momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0) : { destination: newY, duration: 0 }; newX = momentumX.destination; newY = momentumY.destination; time = Math.max(momentumX.duration, momentumY.duration); this.isInTransition = 1; } // INSERT POINT: _end if ( newX != this.x || newY != this.y ) { // change easing function when scroller goes out of the boundaries if ( newX > 0 || newX < this.maxScrollX || newY > 0 || newY < this.maxScrollY ) { easing = utils.ease.quadratic; } this.scrollTo(newX, newY, time, easing); return; } this._execEvent('scrollEnd'); }, _resize: function () { var that = this; clearTimeout(this.resizeTimeout); this.resizeTimeout = setTimeout(function () { that.refresh(); }, this.options.resizePolling); }, resetPosition: function (time) { var x = this.x, y = this.y; time = time || 0; if ( !this.hasHorizontalScroll || this.x > 0 ) { x = 0; } else if ( this.x < this.maxScrollX ) { x = this.maxScrollX; } if ( !this.hasVerticalScroll || this.y > 0 ) { y = 0; } else if ( this.y < this.maxScrollY ) { y = this.maxScrollY; } if ( x == this.x && y == this.y ) { return false; } this.scrollTo(x, y, time, this.options.bounceEasing); return true; }, disable: function () { this.enabled = false; }, enable: function () { this.enabled = true; }, refresh: function () { var rf = this.wrapper.offsetHeight; // Force reflow this.wrapperWidth = this.wrapper.clientWidth; this.wrapperHeight = this.wrapper.clientHeight; /* REPLACE START: refresh */ this.scrollerWidth = this.scroller.offsetWidth; this.scrollerHeight = this.scroller.offsetHeight; /* REPLACE END: refresh */ this.maxScrollX = this.wrapperWidth - this.scrollerWidth; this.maxScrollY = this.wrapperHeight - this.scrollerHeight; this.hasHorizontalScroll = this.options.scrollX && this.maxScrollX < 0; this.hasVerticalScroll = this.options.scrollY && this.maxScrollY < 0; if ( !this.hasHorizontalScroll ) { this.maxScrollX = 0; this.scrollerWidth = this.wrapperWidth; } if ( !this.hasVerticalScroll ) { this.maxScrollY = 0; this.scrollerHeight = this.wrapperHeight; } this.endTime = 0; this.directionX = 0; this.directionY = 0; this.wrapperOffset = utils.offset(this.wrapper); this._execEvent('refresh'); this.resetPosition(); // INSERT POINT: _refresh }, on: function (type, fn) { if ( !this._events[type] ) { this._events[type] = []; } this._events[type].push(fn); }, _execEvent: function (type) { if ( !this._events[type] ) { return; } var i = 0, l = this._events[type].length; if ( !l ) { return; } for ( ; i < l; i++ ) { this._events[type][i].call(this); } }, scrollBy: function (x, y, time, easing) { x = this.x + x; y = this.y + y; time = time || 0; this.scrollTo(x, y, time, easing); }, scrollTo: function (x, y, time, easing) { easing = easing || utils.ease.circular; if ( !time || (this.options.useTransition && easing.style) ) { this._transitionTimingFunction(easing.style); this._transitionTime(time); this._translate(x, y); } else { this._animate(x, y, time, easing.fn); } }, scrollToElement: function (el, time, offsetX, offsetY, easing) { el = el.nodeType ? el : this.scroller.querySelector(el); if ( !el ) { return; } var pos = utils.offset(el); pos.left -= this.wrapperOffset.left; pos.top -= this.wrapperOffset.top; // if offsetX/Y are true we center the element to the screen if ( offsetX === true ) { offsetX = Math.round(el.offsetWidth / 2 - this.wrapper.offsetWidth / 2); } if ( offsetY === true ) { offsetY = Math.round(el.offsetHeight / 2 - this.wrapper.offsetHeight / 2); } pos.left -= offsetX || 0; pos.top -= offsetY || 0; pos.left = pos.left > 0 ? 0 : pos.left < this.maxScrollX ? this.maxScrollX : pos.left; pos.top = pos.top > 0 ? 0 : pos.top < this.maxScrollY ? this.maxScrollY : pos.top; time = time === undefined || time === null || time === 'auto' ? Math.max(Math.abs(this.x-pos.left), Math.abs(this.y-pos.top)) : time; this.scrollTo(pos.left, pos.top, time, easing); }, _transitionTime: function (time) { time = time || 0; this.scrollerStyle[utils.style.transitionDuration] = time + 'ms'; // INSERT POINT: _transitionTime }, _transitionTimingFunction: function (easing) { this.scrollerStyle[utils.style.transitionTimingFunction] = easing; // INSERT POINT: _transitionTimingFunction }, _translate: function (x, y) { if ( this.options.useTransform ) { /* REPLACE START: _translate */ this.scrollerStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.translateZ; /* REPLACE END: _translate */ } else { x = Math.round(x); y = Math.round(y); this.scrollerStyle.left = x + 'px'; this.scrollerStyle.top = y + 'px'; } this.x = x; this.y = y; // INSERT POINT: _translate }, _initEvents: function (remove) { var eventType = remove ? utils.removeEvent : utils.addEvent, target = this.options.bindToWrapper ? this.wrapper : window; eventType(window, 'orientationchange', this); eventType(window, 'resize', this); if ( this.options.click ) { eventType(this.wrapper, 'click', this, true); } if ( !this.options.disableMouse ) { eventType(this.wrapper, 'mousedown', this); eventType(target, 'mousemove', this); eventType(target, 'mousecancel', this); eventType(target, 'mouseup', this); } if ( utils.hasPointer && !this.options.disablePointer ) { eventType(this.wrapper, 'MSPointerDown', this); eventType(target, 'MSPointerMove', this); eventType(target, 'MSPointerCancel', this); eventType(target, 'MSPointerUp', this); } if ( utils.hasTouch && !this.options.disableTouch ) { eventType(this.wrapper, 'touchstart', this); eventType(target, 'touchmove', this); eventType(target, 'touchcancel', this); eventType(target, 'touchend', this); } eventType(this.scroller, 'transitionend', this); eventType(this.scroller, 'webkitTransitionEnd', this); eventType(this.scroller, 'oTransitionEnd', this); eventType(this.scroller, 'MSTransitionEnd', this); }, getComputedPosition: function () { var matrix = window.getComputedStyle(this.scroller, null), x, y; if ( this.options.useTransform ) { matrix = matrix[utils.style.transform].split(')')[0].split(', '); x = +(matrix[12] || matrix[4]); y = +(matrix[13] || matrix[5]); } else { x = +matrix.left.replace(/[^-\d]/g, ''); y = +matrix.top.replace(/[^-\d]/g, ''); } return { x: x, y: y }; }, _animate: function (destX, destY, duration, easingFn) { var that = this, startX = this.x, startY = this.y, startTime = utils.getTime(), destTime = startTime + duration; function step () { var now = utils.getTime(), newX, newY, easing; if ( now >= destTime ) { that.isAnimating = false; that._translate(destX, destY); if ( !that.resetPosition(that.options.bounceTime) ) { that._execEvent('scrollEnd'); } return; } now = ( now - startTime ) / duration; easing = easingFn(now); newX = ( destX - startX ) * easing + startX; newY = ( destY - startY ) * easing + startY; that._translate(newX, newY); if ( that.isAnimating ) { rAF(step); } } this.isAnimating = true; step(); }, handleEvent: function (e) { switch ( e.type ) { case 'touchstart': case 'MSPointerDown': case 'mousedown': this._start(e); break; case 'touchmove': case 'MSPointerMove': case 'mousemove': this._move(e); break; case 'touchend': case 'MSPointerUp': case 'mouseup': case 'touchcancel': case 'MSPointerCancel': case 'mousecancel': this._end(e); break; case 'orientationchange': case 'resize': this._resize(); break; case 'transitionend': case 'webkitTransitionEnd': case 'oTransitionEnd': case 'MSTransitionEnd': this._transitionEnd(e); break; case 'DOMMouseScroll': case 'mousewheel': this._wheel(e); break; case 'keydown': this._key(e); break; case 'click': if ( !e._constructed ) { e.preventDefault(); e.stopPropagation(); } break; } } }; IScroll.ease = utils.ease; return IScroll; })(window, document, Math); /** * MicroEvent - to make any js object an event emitter (server or browser) * * - pure javascript - server compatible, browser compatible * - dont rely on the browser doms * - super simple - you get it immediatly, no mistery, no magic involved * * - create a MicroEventDebug with goodies to debug * - make it safer to use */ /** NOTE: This library is customized for Onsen UI. */ var MicroEvent = function(){}; MicroEvent.prototype = { on : function(event, fct){ this._events = this._events || {}; this._events[event] = this._events[event] || []; this._events[event].push(fct); }, once : function(event, fct){ var self = this; var wrapper = function() { self.off(event, wrapper); return fct.apply(null, arguments); }; this.on(event, wrapper); }, off : function(event, fct){ this._events = this._events || {}; if( event in this._events === false ) return; this._events[event].splice(this._events[event].indexOf(fct), 1); }, emit : function(event /* , args... */){ this._events = this._events || {}; if( event in this._events === false ) return; for(var i = 0; i < this._events[event].length; i++){ this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1)); } } }; /** * mixin will delegate all MicroEvent.js function in the destination object * * - require('MicroEvent').mixin(Foobar) will make Foobar able to use MicroEvent * * @param {Object} the object which will support MicroEvent */ MicroEvent.mixin = function(destObject){ var props = ['on', 'once', 'off', 'emit']; for(var i = 0; i < props.length; i ++){ if( typeof destObject === 'function' ){ destObject.prototype[props[i]] = MicroEvent.prototype[props[i]]; }else{ destObject[props[i]] = MicroEvent.prototype[props[i]]; } } } // export in common js if( typeof module !== "undefined" && ('exports' in module)){ module.exports = MicroEvent; } /* Modernizr 2.6.2 (Custom Build) | MIT & BSD * Build: http://modernizr.com/download/#-borderradius-boxshadow-cssanimations-csstransforms-csstransforms3d-csstransitions-canvas-svg-shiv-cssclasses-teststyles-testprop-testallprops-prefixes-domprefixes-load */ ; window.Modernizr = (function( window, document, undefined ) { var version = '2.6.2', Modernizr = {}, enableClasses = true, docElement = document.documentElement, mod = 'modernizr', modElem = document.createElement(mod), mStyle = modElem.style, inputElem , toString = {}.toString, prefixes = ' -webkit- -moz- -o- -ms- '.split(' '), omPrefixes = 'Webkit Moz O ms', cssomPrefixes = omPrefixes.split(' '), domPrefixes = omPrefixes.toLowerCase().split(' '), ns = {'svg': 'http://www.w3.org/2000/svg'}, tests = {}, inputs = {}, attrs = {}, classes = [], slice = classes.slice, featureName, injectElementWithStyles = function( rule, callback, nodes, testnames ) { var style, ret, node, docOverflow, div = document.createElement('div'), body = document.body, fakeBody = body || document.createElement('body'); if ( parseInt(nodes, 10) ) { while ( nodes-- ) { node = document.createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } style = ['&#173;','<style id="s', mod, '">', rule, '</style>'].join(''); div.id = mod; (body ? div : fakeBody).innerHTML += style; fakeBody.appendChild(div); if ( !body ) { fakeBody.style.background = ''; fakeBody.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(fakeBody); } ret = callback(div, rule); if ( !body ) { fakeBody.parentNode.removeChild(fakeBody); docElement.style.overflow = docOverflow; } else { div.parentNode.removeChild(div); } return !!ret; }, _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp; if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) { hasOwnProp = function (object, property) { return _hasOwnProperty.call(object, property); }; } else { hasOwnProp = function (object, property) { return ((property in object) && is(object.constructor.prototype[property], 'undefined')); }; } if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { var target = this; if (typeof target != "function") { throw new TypeError(); } var args = slice.call(arguments, 1), bound = function () { if (this instanceof bound) { var F = function(){}; F.prototype = target.prototype; var self = new F(); var result = target.apply( self, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return self; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; return bound; }; } function setCss( str ) { mStyle.cssText = str; } function setCssAll( str1, str2 ) { return setCss(prefixes.join(str1 + ';') + ( str2 || '' )); } function is( obj, type ) { return typeof obj === type; } function contains( str, substr ) { return !!~('' + str).indexOf(substr); } function testProps( props, prefixed ) { for ( var i in props ) { var prop = props[i]; if ( !contains(prop, "-") && mStyle[prop] !== undefined ) { return prefixed == 'pfx' ? prop : true; } } return false; } function testDOMProps( props, obj, elem ) { for ( var i in props ) { var item = obj[props[i]]; if ( item !== undefined) { if (elem === false) return props[i]; if (is(item, 'function')){ return item.bind(elem || obj); } return item; } } return false; } function testPropsAll( prop, prefixed, elem ) { var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1), props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); if(is(prefixed, "string") || is(prefixed, "undefined")) { return testProps(props, prefixed); } else { props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); return testDOMProps(props, prefixed, elem); } } tests['canvas'] = function() { var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); }; tests['borderradius'] = function() { return testPropsAll('borderRadius'); }; tests['boxshadow'] = function() { return testPropsAll('boxShadow'); }; tests['cssanimations'] = function() { return testPropsAll('animationName'); }; tests['csstransforms'] = function() { return !!testPropsAll('transform'); }; tests['csstransforms3d'] = function() { var ret = !!testPropsAll('perspective'); if ( ret && 'webkitPerspective' in docElement.style ) { injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) { ret = node.offsetLeft === 9 && node.offsetHeight === 3; }); } return ret; }; tests['csstransitions'] = function() { return testPropsAll('transition'); }; tests['svg'] = function() { return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect; }; for ( var feature in tests ) { if ( hasOwnProp(tests, feature) ) { featureName = feature.toLowerCase(); Modernizr[featureName] = tests[feature](); classes.push((Modernizr[featureName] ? '' : 'no-') + featureName); } } Modernizr.addTest = function ( feature, test ) { if ( typeof feature == 'object' ) { for ( var key in feature ) { if ( hasOwnProp( feature, key ) ) { Modernizr.addTest( key, feature[ key ] ); } } } else { feature = feature.toLowerCase(); if ( Modernizr[feature] !== undefined ) { return Modernizr; } test = typeof test == 'function' ? test() : test; if (typeof enableClasses !== "undefined" && enableClasses) { docElement.className += ' ' + (test ? '' : 'no-') + feature; } Modernizr[feature] = test; } return Modernizr; }; setCss(''); modElem = inputElem = null; ;(function(window, document) { var options = window.html5 || {}; var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i; var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; var supportsHtml5Styles; var expando = '_html5shiv'; var expanID = 0; var expandoData = {}; var supportsUnknownElements; (function() { try { var a = document.createElement('a'); a.innerHTML = '<xyz></xyz>'; supportsHtml5Styles = ('hidden' in a); supportsUnknownElements = a.childNodes.length == 1 || (function() { (document.createElement)('a'); var frag = document.createDocumentFragment(); return ( typeof frag.cloneNode == 'undefined' || typeof frag.createDocumentFragment == 'undefined' || typeof frag.createElement == 'undefined' ); }()); } catch(e) { supportsHtml5Styles = true; supportsUnknownElements = true; } }()); function addStyleSheet(ownerDocument, cssText) { var p = ownerDocument.createElement('p'), parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; p.innerHTML = 'x<style>' + cssText + '</style>'; return parent.insertBefore(p.lastChild, parent.firstChild); } function getElements() { var elements = html5.elements; return typeof elements == 'string' ? elements.split(' ') : elements; } function getExpandoData(ownerDocument) { var data = expandoData[ownerDocument[expando]]; if (!data) { data = {}; expanID++; ownerDocument[expando] = expanID; expandoData[expanID] = data; } return data; } function createElement(nodeName, ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createElement(nodeName); } if (!data) { data = getExpandoData(ownerDocument); } var node; if (data.cache[nodeName]) { node = data.cache[nodeName].cloneNode(); } else if (saveClones.test(nodeName)) { node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); } else { node = data.createElem(nodeName); } return node.canHaveChildren && !reSkip.test(nodeName) ? data.frag.appendChild(node) : node; } function createDocumentFragment(ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createDocumentFragment(); } data = data || getExpandoData(ownerDocument); var clone = data.frag.cloneNode(), i = 0, elems = getElements(), l = elems.length; for(;i<l;i++){ clone.createElement(elems[i]); } return clone; } function shivMethods(ownerDocument, data) { if (!data.cache) { data.cache = {}; data.createElem = ownerDocument.createElement; data.createFrag = ownerDocument.createDocumentFragment; data.frag = data.createFrag(); } ownerDocument.createElement = function(nodeName) { if (!html5.shivMethods) { return data.createElem(nodeName); } return createElement(nodeName, ownerDocument, data); }; ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' + 'var n=f.cloneNode(),c=n.createElement;' + 'h.shivMethods&&(' + getElements().join().replace(/\w+/g, function(nodeName) { data.createElem(nodeName); data.frag.createElement(nodeName); return 'c("' + nodeName + '")'; }) + ');return n}' )(html5, data.frag); } function shivDocument(ownerDocument) { if (!ownerDocument) { ownerDocument = document; } var data = getExpandoData(ownerDocument); if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) { data.hasCSS = !!addStyleSheet(ownerDocument, 'article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}' + 'mark{background:#FF0;color:#000}' ); } if (!supportsUnknownElements) { shivMethods(ownerDocument, data); } return ownerDocument; } var html5 = { 'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video', 'shivCSS': (options.shivCSS !== false), 'supportsUnknownElements': supportsUnknownElements, 'shivMethods': (options.shivMethods !== false), 'type': 'default', 'shivDocument': shivDocument, createElement: createElement, createDocumentFragment: createDocumentFragment }; window.html5 = html5; shivDocument(document); }(this, document)); Modernizr._version = version; Modernizr._prefixes = prefixes; Modernizr._domPrefixes = domPrefixes; Modernizr._cssomPrefixes = cssomPrefixes; Modernizr.testProp = function(prop){ return testProps([prop]); }; Modernizr.testAllProps = testPropsAll; Modernizr.testStyles = injectElementWithStyles; docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + (enableClasses ? ' js ' + classes.join(' ') : ''); return Modernizr; })(this, this.document); /*yepnope1.5.4|WTFPL*/ (function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}})(this,document); Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0));}; ; /* Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function (global, undefined) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var setImmediate; function addFromSetImmediateArguments(args) { tasksByHandle[nextHandle] = partiallyApplied.apply(undefined, args); return nextHandle++; } // This function accepts the same arguments as setImmediate, but // returns a function that requires no arguments. function partiallyApplied(handler) { var args = [].slice.call(arguments, 1); return function() { if (typeof handler === "function") { handler.apply(undefined, args); } else { (new Function("" + handler))(); } }; } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(partiallyApplied(runIfPresent, handle), 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { task(); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function clearImmediate(handle) { delete tasksByHandle[handle]; } function installNextTickImplementation() { setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); process.nextTick(partiallyApplied(runIfPresent, handle)); return handle; }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); global.postMessage(messagePrefix + handle, "*"); return handle; }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); channel.port2.postMessage(handle); return handle; }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); return handle; }; } function installSetTimeoutImplementation() { setImmediate = function() { var handle = addFromSetImmediateArguments(arguments); setTimeout(partiallyApplied(runIfPresent, handle), 0); return handle; }; } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if ({}.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 installNextTickImplementation(); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(); } else if (global.MessageChannel) { // For web workers, where supported installMessageChannelImplementation(); } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6–8 installReadyStateChangeImplementation(); } else { // For older browsers installSetTimeoutImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate; }(new Function("return this")())); (function() { function Viewport() { this.PRE_IOS7_VIEWPORT = "initial-scale=1, maximum-scale=1, user-scalable=no"; this.IOS7_VIEWPORT = "initial-scale=1, maximum-scale=1, user-scalable=no"; this.DEFAULT_VIEWPORT = "initial-scale=1, maximum-scale=1, user-scalable=no"; this.ensureViewportElement(); this.platform = {}; this.platform.name = this.getPlatformName(); this.platform.version = this.getPlatformVersion(); return this; }; Viewport.prototype.ensureViewportElement = function(){ this.viewportElement = document.querySelector('meta[name=viewport]'); if(!this.viewportElement){ this.viewportElement = document.createElement('meta'); this.viewportElement.name = "viewport"; document.head.appendChild(this.viewportElement); } }, Viewport.prototype.setup = function() { if (!this.viewportElement) { return; } if (this.viewportElement.getAttribute('data-no-adjust') == "true") { return; } if (this.platform.name == 'ios') { if (this.platform.version >= 7 && isWebView()) { this.viewportElement.setAttribute('content', this.IOS7_VIEWPORT); } else { this.viewportElement.setAttribute('content', this.PRE_IOS7_VIEWPORT); } } else { this.viewportElement.setAttribute('content', this.DEFAULT_VIEWPORT); } function isWebView() { return !!(window.cordova || window.phonegap || window.PhoneGap); } }; Viewport.prototype.getPlatformName = function() { if (navigator.userAgent.match(/Android/i)) { return "android"; } if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) { return "ios"; } // unknown return undefined; }; Viewport.prototype.getPlatformVersion = function() { var start = window.navigator.userAgent.indexOf('OS '); return window.Number(window.navigator.userAgent.substr(start + 3, 3).replace('_', '.')); }; window.Viewport = Viewport; })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/back_button.tpl', '<span \n' + ' class="toolbar-button--quiet {{modifierTemplater(\'toolbar-button--*\')}}" \n' + ' ng-click="$root.ons.findParentComponentUntil(\'ons-navigator\', $event).popPage({cancelIfRunning: true})"\n' + ' ng-show="showBackButton"\n' + ' style="height: 44px; line-height: 0; padding: 0 10px 0 0; position: relative;">\n' + ' \n' + ' <i \n' + ' class="ion-ios-arrow-back ons-back-button__icon" \n' + ' style="vertical-align: top; background-color: transparent; height: 44px; line-height: 44px; font-size: 36px; margin-left: 8px; margin-right: 2px; width: 16px; display: inline-block; padding-top: 1px;"></i>\n' + '\n' + ' <span \n' + ' style="vertical-align: top; display: inline-block; line-height: 44px; height: 44px;" \n' + ' class="back-button__label"></span>\n' + '</span>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/button.tpl', '<span class="label ons-button-inner"></span>\n' + '<span class="spinner button__spinner {{modifierTemplater(\'button--*__spinner\')}}"></span>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/dialog.tpl', '<div class="dialog-mask"></div>\n' + '<div class="dialog {{ modifierTemplater(\'dialog--*\') }}"></div>\n' + '</div>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/icon.tpl', '<i class="fa fa-{{icon}} fa-{{spin}} fa-{{fixedWidth}} fa-rotate-{{rotate}} fa-flip-{{flip}}" ng-class="sizeClass" ng-style="style"></i>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/popover.tpl', '<div class="popover-mask"></div>\n' + '<div class="popover popover--{{ direction }} {{ modifierTemplater(\'popover--*\') }}">\n' + ' <div class="popover__content {{ modifierTemplater(\'popover__content--*\') }}"></div>\n' + ' <div class="popover__{{ arrowPosition }}-arrow"></div>\n' + '</div>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/row.tpl', '<div class="row row-{{align}} ons-row-inner"></div>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/sliding_menu.tpl', '<div class="onsen-sliding-menu__menu ons-sliding-menu-inner"></div>\n' + '<div class="onsen-sliding-menu__main ons-sliding-menu-inner"></div>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/split_view.tpl', '<div class="onsen-split-view__secondary full-screen ons-split-view-inner"></div>\n' + '<div class="onsen-split-view__main full-screen ons-split-view-inner"></div>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/switch.tpl', '<label class="switch {{modifierTemplater(\'switch--*\')}}">\n' + ' <input type="checkbox" class="switch__input {{modifierTemplater(\'switch--*__input\')}}" ng-model="model">\n' + ' <div class="switch__toggle {{modifierTemplater(\'switch--*__toggle\')}}"></div>\n' + '</label>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/tab.tpl', '<input type="radio" name="tab-bar-{{tabbarId}}" style="display: none">\n' + '<button class="tab-bar__button tab-bar-inner {{tabbarModifierTemplater(\'tab-bar--*__button\')}} {{modifierTemplater(\'tab-bar__button--*\')}}" ng-click="tryToChange()">\n' + '</button>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/tab_bar.tpl', '<div class="ons-tab-bar__content tab-bar__content"></div>\n' + '<div ng-hide="hideTabs" class="tab-bar ons-tab-bar__footer {{modifierTemplater(\'tab-bar--*\')}} ons-tabbar-inner"></div>\n' + ''); }]); })(); (function(module) { try { module = angular.module('templates-main'); } catch(err) { module = angular.module('templates-main', []); } module.run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('templates/toolbar_button.tpl', '<span class="toolbar-button {{modifierTemplater(\'toolbar-button--*\')}} navigation-bar__line-height" ng-transclude></span>\n' + ''); }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ window.DoorLock = (function() { /** * Door locking system. * * @param {Object} [options] * @param {Function} [options.log] */ var DoorLock = function(options) { options = options || {}; this._lockList = []; this._waitList = []; this._log = options.log || function() {}; }; DoorLock.generateId = (function() { var i = 0; return function() { return i++; }; })(); DoorLock.prototype = { /** * Register a lock. * * @return {Function} Callback for unlocking. */ lock: function() { var self = this; var unlock = function() { self._unlock(unlock); }; unlock.id = DoorLock.generateId(); this._lockList.push(unlock); this._log('lock: ' + (unlock.id)); return unlock; }, _unlock: function(fn) { var index = this._lockList.indexOf(fn); if (index === -1) { throw new Error('This function is not registered in the lock list.'); } this._lockList.splice(index, 1); this._log('unlock: ' + fn.id); this._tryToFreeWaitList(); }, _tryToFreeWaitList: function() { while (!this.isLocked() && this._waitList.length > 0) { this._waitList.shift()(); } }, /** * Register a callback for waiting unlocked door. * * @params {Function} callback Callback on unlocking the door completely. */ waitUnlock: function(callback) { if (!(callback instanceof Function)) { throw new Error('The callback param must be a function.'); } if (this.isLocked()) { this._waitList.push(callback); } else { callback(); } }, /** * @return {Boolean} */ isLocked: function() { return this._lockList.length > 0; } }; return DoorLock; })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @ngdoc object * @name ons * @category util * @description * [ja]Onsen UIで利用できるグローバルなオブジェクトです。このオブジェクトは、AngularJSのスコープから参照することができます。 [/ja] * [en]A global object that's used in Onsen UI. This object can be reached from the AngularJS scope.[/en] */ /** * @ngdoc method * @signature ready(callback) * @description * [ja]アプリの初期化に利用するメソッドです。渡された関数は、Onsen UIの初期化が終了している時点で必ず呼ばれます。[/ja] * [en]Method used to wait for app initialization. The callback will not be executed until Onsen UI has been completely initialized.[/en] * @param {Function} callback * [en]Function that executes after Onsen UI has been initialized.[/en] * [ja]Onsen UIが初期化が完了した後に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature bootstrap([moduleName, [dependencies]]) * @description * [ja]Onsen UIの初期化を行います。Angular.jsのng-app属性を利用すること無しにOnsen UIを読み込んで初期化してくれます。[/ja] * [en]Initialize Onsen UI. Can be used to load Onsen UI without using the <code>ng-app</code> attribute from AngularJS.[/en] * @param {String} [moduleName] * [en]AngularJS module name.[/en] * [ja]Angular.jsでのモジュール名[/ja] * @param {Array} [dependencies] * [en]List of AngularJS module dependencies.[/en] * [ja]依存するAngular.jsのモジュール名の配列[/ja] * @return {Object} * [en]An AngularJS module object.[/en] * [ja]AngularJSのModuleオブジェクトを表します。[/ja] */ /** * @ngdoc method * @signature enableAutoStatusBarFill() * @description * [en]Enable status bar fill feature on iOS7 and above.[/en] * [ja]iOS7以上で、ステータスバー部分の高さを自動的に埋める処理を有効にします。[/ja] */ /** * @ngdoc method * @signature disableAutoStatusBarFill() * @description * [en]Disable status bar fill feature on iOS7 and above.[/en] * [ja]iOS7以上で、ステータスバー部分の高さを自動的に埋める処理を無効にします。[/ja] */ /** * @ngdoc method * @signature findParentComponentUntil(name, [dom]) * @param {String} name * [en]Name of component, i.e. 'ons-page'.[/en] * [ja]コンポーネント名を指定します。例えばons-pageなどを指定します。[/ja] * @param {Object|jqLite|HTMLElement} [dom] * [en]$event, jqLite or HTMLElement object.[/en] * [ja]$eventオブジェクト、jqLiteオブジェクト、HTMLElementオブジェクトのいずれかを指定できます。[/ja] * @return {Object} * [en]Component object. Will return null if no component was found.[/en] * [ja]コンポーネントのオブジェクトを返します。もしコンポーネントが見つからなかった場合にはnullを返します。[/ja] * @description * [en]Find parent component object of <code>dom</code> element.[/en] * [ja]指定されたdom引数の親要素をたどってコンポーネントを検索します。[/ja] */ /** * @ngdoc method * @signature findComponent(selector, [dom]) * @param {String} selector * [en]CSS selector[/en] * [ja]CSSセレクターを指定します。[/ja] * @param {HTMLElement} [dom] * [en]DOM element to search from.[/en] * [ja]検索対象とするDOM要素を指定します。[/ja] * @return {Object} * [en]Component object. Will return null if no component was found.[/en] * [ja]コンポーネントのオブジェクトを返します。もしコンポーネントが見つからなかった場合にはnullを返します。[/ja] * @description * [en]Find component object using CSS selector.[/en] * [ja]CSSセレクタを使ってコンポーネントのオブジェクトを検索します。[/ja] */ /** * @ngdoc method * @signature setDefaultDeviceBackButtonListener(listener) * @param {Function} listener * [en]Function that executes when device back button is pressed.[/en] * [ja]デバイスのバックボタンが押された時に実行される関数オブジェクトを指定します。[/ja] * @description * [en]Set default handler for device back button.[/en] * [ja]デバイスのバックボタンのためのデフォルトのハンドラを設定します。[/ja] */ /** * @ngdoc method * @signature disableDeviceBackButtonHandler() * @description * [en]Disable device back button event handler.[/en] * [ja]デバイスのバックボタンのイベントを受け付けないようにします。[/ja] */ /** * @ngdoc method * @signature enableDeviceBackButtonHandler() * @description * [en]Enable device back button event handler.[/en] * [ja]デバイスのバックボタンのイベントを受け付けるようにします。[/ja] */ /** * @ngdoc method * @signature isReady() * @return {Boolean} * [en]Will be true if Onsen UI is initialized.[/en] * [ja]初期化されているかどうかを返します。[/ja] * @description * [en]Returns true if Onsen UI is initialized.[/en] * [ja]Onsen UIがすでに初期化されているかどうかを返すメソッドです。[/ja] */ /** * @ngdoc method * @signature compile(dom) * @param {HTMLElement} dom * [en]Element to compile.[/en] * [ja]コンパイルする要素を指定します。[/ja] * @description * [en]Compile Onsen UI components.[/en] * [ja]通常のHTMLの要素をOnsen UIのコンポーネントにコンパイルします。[/ja] */ /** * @ngdoc method * @signature isWebView() * @return {Boolean} * [en]Will be true if the app is running in Cordova.[/en] * [ja]Cordovaで実行されている場合にtrueになります。[/ja] * @description * [en]Returns true if running inside Cordova.[/en] * [ja]Cordovaで実行されているかどうかを返すメソッドです。[/ja] */ /** * @ngdoc method * @signature createAlertDialog(page, [options]) * @param {String} page * [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-alert-dialog> component.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Object} [options.parentScope] * [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en] * [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。[/ja] * @return {Promise} * [en]Promise object that resolves to the alert dialog component object.[/en] * [ja]ダイアログのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja] * @description * [en]Create a alert dialog instance from a template.[/en] * [ja]テンプレートからアラートダイアログのインスタンスを生成します。[/ja] */ /** * @ngdoc method * @signature createDialog(page, [options]) * @param {String} page * [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-dialog> component.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Object} [options.parentScope] * [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en] * [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。[/ja] * @return {Promise} * [en]Promise object that resolves to the dialog component object.[/en] * [ja]ダイアログのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja] * @description * [en]Create a dialog instance from a template.[/en] * [ja]テンプレートからダイアログのインスタンスを生成します。[/ja] */ /** * @ngdoc method * @signature createPopover(page, [options]) * @param {String} page * [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-dialog> component.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Object} [options.parentScope] * [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en] * [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。[/ja] * @return {Promise} * [en]Promise object that resolves to the popover component object.[/en] * [ja]ポップオーバーのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja] * @description * [en]Create a popover instance from a template.[/en] * [ja]テンプレートからポップオーバーのインスタンスを生成します。[/ja] */ window.ons = (function(){ 'use strict'; var module = angular.module('onsen', ['templates-main']); angular.module('onsen.directives', ['onsen']); // for BC // JS Global facade for Onsen UI. var ons = createOnsenFacade(); initKeyboardEvents(); waitDeviceReady(); waitOnsenUILoad(); initAngularModule(); return ons; function waitDeviceReady() { var unlockDeviceReady = ons._readyLock.lock(); window.addEventListener('DOMContentLoaded', function() { if (ons.isWebView()) { window.document.addEventListener('deviceready', unlockDeviceReady, false); } else { unlockDeviceReady(); } }, false); } function waitOnsenUILoad() { var unlockOnsenUI = ons._readyLock.lock(); module.run(['$compile', '$rootScope', '$onsen', function($compile, $rootScope, $onsen) { // for initialization hook. if (document.readyState === 'loading' || document.readyState == 'uninitialized') { window.addEventListener('DOMContentLoaded', function() { document.body.appendChild(document.createElement('ons-dummy-for-init')); }); } else if (document.body) { document.body.appendChild(document.createElement('ons-dummy-for-init')); } else { throw new Error('Invalid initialization state.'); } $rootScope.$on('$ons-ready', unlockOnsenUI); }]); } function initAngularModule() { module.value('$onsGlobal', ons); module.run(['$compile', '$rootScope', '$onsen', '$q', function($compile, $rootScope, $onsen, $q) { ons._onsenService = $onsen; ons._qService = $q; $rootScope.ons = window.ons; $rootScope.console = window.console; $rootScope.alert = window.alert; ons.$compile = $compile; }]); } function initKeyboardEvents() { ons.softwareKeyboard = new MicroEvent(); ons.softwareKeyboard._visible = false; var onShow = function() { ons.softwareKeyboard._visible = true; ons.softwareKeyboard.emit('show'); }, onHide = function() { ons.softwareKeyboard._visible = false; ons.softwareKeyboard.emit('hide'); }; var bindEvents = function() { if (typeof Keyboard !== 'undefined') { // https://github.com/martinmose/cordova-keyboard/blob/95f3da3a38d8f8e1fa41fbf40145352c13535a00/README.md Keyboard.onshow = onShow; Keyboard.onhide = onHide; ons.softwareKeyboard.emit('init', {visible: Keyboard.isVisible}); return true; } else if (typeof cordova.plugins !== 'undefined' && typeof cordova.plugins.Keyboard !== 'undefined') { // https://github.com/driftyco/ionic-plugins-keyboard/blob/ca27ecf/README.md window.addEventListener('native.keyboardshow', onShow); window.addEventListener('native.keyboardhide', onHide); ons.softwareKeyboard.emit('init', {visible: cordova.plugins.Keyboard.isVisible}); return true; } return false; }; var noPluginError = function() { console.warn('ons-keyboard: Cordova Keyboard plugin is not present.'); }; document.addEventListener('deviceready', function() { if (!bindEvents()) { if (document.querySelector('[ons-keyboard-active]') || document.querySelector('[ons-keyboard-inactive]')) { noPluginError(); } ons.softwareKeyboard.on = noPluginError; } }); } function createOnsenFacade() { var ons = { _readyLock: new DoorLock(), _onsenService: null, _config: { autoStatusBarFill: true }, _unlockersDict: {}, // Object to attach component variables to when using the var="..." attribute. // Can be set to null to avoid polluting the global scope. componentBase: window, /** * Bootstrap this document as a Onsen UI application. * * @param {String} [name] optional name * @param {Array} [deps] optional dependency modules */ bootstrap : function(name, deps) { if (angular.isArray(name)) { deps = name; name = undefined; } if (!name) { name = 'myOnsenApp'; } deps = ['onsen'].concat(angular.isArray(deps) ? deps : []); var module = angular.module(name, deps); var doc = window.document; if (doc.readyState == 'loading' || doc.readyState == 'uninitialized' || doc.readyState == 'interactive') { doc.addEventListener('DOMContentLoaded', function() { angular.bootstrap(doc.documentElement, [name]); }, false); } else if (doc.documentElement) { angular.bootstrap(doc.documentElement, [name]); } else { throw new Error('Invalid state'); } return module; }, /** * Enable status bar fill feature on iOS7 and above. */ enableAutoStatusBarFill: function() { if (this.isReady()) { throw new Error('This method must be called before ons.isReady() is true.'); } this._config.autoStatusBarFill = true; }, /** * Disable status bar fill feature on iOS7 and above. */ disableAutoStatusBarFill: function() { if (this.isReady()) { throw new Error('This method must be called before ons.isReady() is true.'); } this._config.autoStatusBarFill = false; }, /** * @param {String} [name] * @param {Object/jqLite/HTMLElement} dom $event object or jqLite object or HTMLElement object. * @return {Object} */ findParentComponentUntil: function(name, dom) { var element; if (dom instanceof HTMLElement) { element = angular.element(dom); } else if (dom instanceof angular.element) { element = dom; } else if (dom.target) { element = angular.element(dom.target); } return element.inheritedData(name); }, /** * @param {Function} listener */ setDefaultDeviceBackButtonListener: function(listener) { this._getOnsenService().getDefaultDeviceBackButtonHandler().setListener(listener); }, /** * Disable this framework to handle cordova "backbutton" event. */ disableDeviceBackButtonHandler: function() { this._getOnsenService().DeviceBackButtonHandler.disable(); }, /** * Enable this framework to handle cordova "backbutton" event. */ enableDeviceBackButtonHandler: function() { this._getOnsenService().DeviceBackButtonHandler.enable(); }, /** * Find view object correspond dom element queried by CSS selector. * * @param {String} selector CSS selector * @param {HTMLElement} [dom] * @return {Object/void} */ findComponent: function(selector, dom) { var target = (dom ? dom : document).querySelector(selector); return target ? angular.element(target).data(target.nodeName.toLowerCase()) || null : null; }, /** * @return {Boolean} */ isReady: function() { return !ons._readyLock.isLocked(); }, /** * @param {HTMLElement} dom */ compile : function(dom) { if (!ons.$compile) { throw new Error('ons.$compile() is not ready. Wait for initialization with ons.ready().'); } if (!(dom instanceof HTMLElement)) { throw new Error('First argument must be an instance of HTMLElement.'); } var scope = angular.element(dom).scope(); if (!scope) { throw new Error('AngularJS Scope is null. Argument DOM element must be attached in DOM document.'); } ons.$compile(dom)(scope); }, _getOnsenService: function() { if (!this._onsenService) { throw new Error('$onsen is not loaded, wait for ons.ready().'); } return this._onsenService; }, /** * @param {Array} [dependencies] * @param {Function} callback */ ready : function(/* dependencies, */callback) { if (callback instanceof Function) { if (ons.isReady()) { callback(); } else { ons._readyLock.waitUnlock(callback); } } else if (angular.isArray(callback) && arguments[1] instanceof Function) { var dependencies = callback; callback = arguments[1]; ons.ready(function() { var $onsen = ons._getOnsenService(); $onsen.waitForVariables(dependencies, callback); }); } }, /** * @return {Boolean} */ isWebView: function() { if (document.readyState === 'loading' || document.readyState == 'uninitialized') { throw new Error('isWebView() method is available after dom contents loaded.'); } return !!(window.cordova || window.phonegap || window.PhoneGap); }, /** * @param {String} page * @param {Object} [options] * @param {Object} [options.parentScope] * @return {Promise} */ createAlertDialog: function(page, options) { options = options || {}; if (!page) { throw new Error('Page url must be defined.'); } var alertDialog = angular.element('<ons-alert-dialog>'), $onsen = this._getOnsenService(); angular.element(document.body).append(angular.element(alertDialog)); return $onsen.getPageHTMLAsync(page).then(function(html) { var div = document.createElement('div'); div.innerHTML = html; var el = angular.element(div.querySelector('ons-alert-dialog')); // Copy attributes and insert html. var attrs = el.prop('attributes'); for (var i = 0, l = attrs.length; i < l; i++) { alertDialog.attr(attrs[i].name, attrs[i].value); } alertDialog.html(el.html()); var parentScope; if (options.parentScope) { parentScope = options.parentScope.$new(); ons.$compile(alertDialog)(parentScope); } else { ons.compile(alertDialog[0]); } if (el.attr('disabled')) { alertDialog.attr('disabled', 'disabled'); } if (parentScope) { alertDialog.data('ons-alert-dialog')._parentScope = parentScope; } return alertDialog.data('ons-alert-dialog'); }); }, /** * @param {String} page * @param {Object} [options] * @param {Object} [options.parentScope] * @return {Promise} */ createDialog: function(page, options) { options = options || {}; if (!page) { throw new Error('Page url must be defined.'); } var dialog = angular.element('<ons-dialog>'), $onsen = this._getOnsenService(); angular.element(document.body).append(angular.element(dialog)); return $onsen.getPageHTMLAsync(page).then(function(html) { var div = document.createElement('div'); div.innerHTML = html; var el = angular.element(div.querySelector('ons-dialog')); // Copy attributes and insert html. var attrs = el.prop('attributes'); for (var i = 0, l = attrs.length; i < l; i++) { dialog.attr(attrs[i].name, attrs[i].value); } dialog.html(el.html()); var parentScope; if (options.parentScope) { parentScope = options.parentScope.$new(); ons.$compile(dialog)(parentScope); } else { ons.compile(dialog[0]); } if (el.attr('disabled')) { dialog.attr('disabled', 'disabled'); } var deferred = ons._qService.defer(); dialog.on('ons-dialog:init', function(e) { // Copy "style" attribute from parent. var child = dialog[0].querySelector('.dialog'); if (el[0].hasAttribute('style')) { var parentStyle = el[0].getAttribute('style'), childStyle = child.getAttribute('style'), newStyle = (function(a, b) { var c = (a.substr(-1) === ';' ? a : a + ';') + (b.substr(-1) === ';' ? b : b + ';'); return c; })(parentStyle, childStyle); child.setAttribute('style', newStyle); } if (parentScope) { e.component._parentScope = parentScope; } deferred.resolve(e.component); }); return deferred.promise; }); }, /** * @param {String} page * @param {Object} [options] * @param {Object} [options.parentScope] * @return {Promise} */ createPopover: function(page, options) { options = options || {}; if (!page) { throw new Error('Page url must be defined.'); } var popover = angular.element('<ons-popover>'), $onsen = this._getOnsenService(); angular.element(document.body).append(angular.element(popover)); return $onsen.getPageHTMLAsync(page).then(function(html) { var div = document.createElement('div'); div.innerHTML = html; var el = angular.element(div.querySelector('ons-popover')); // Copy attributes and insert html. var attrs = el.prop('attributes'); for (var i = 0, l = attrs.length; i < l; i++) { popover.attr(attrs[i].name, attrs[i].value); } popover.html(el.html()); var parentScope; if (options.parentScope) { parentScope = options.parentScope.$new(); ons.$compile(popover)(parentScope); } else { ons.compile(popover[0]); } if (el.attr('disabled')) { popover.attr('disabled', 'disabled'); } var deferred = ons._qService.defer(); popover.on('ons-popover:init', function(e) { // Copy "style" attribute from parent. var child = popover[0].querySelector('.popover'); if (el[0].hasAttribute('style')) { var parentStyle = el[0].getAttribute('style'), childStyle = child.getAttribute('style'), newStyle = (function(a, b) { var c = (a.substr(-1) === ';' ? a : a + ';') + (b.substr(-1) === ';' ? b : b + ';'); return c; })(parentStyle, childStyle); child.setAttribute('style', newStyle); } if (parentScope) { e.component._parentScope = parentScope; } deferred.resolve(e.component); }); return deferred.promise; }); } }; return ons; } })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('AlertDialogView', ['$onsen', 'DialogAnimator', 'SlideDialogAnimator', 'AndroidAlertDialogAnimator', 'IOSAlertDialogAnimator', function($onsen, DialogAnimator, SlideDialogAnimator, AndroidAlertDialogAnimator, IOSAlertDialogAnimator) { var AlertDialogView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs) { this._scope = scope; this._element = element; this._attrs = attrs; this._element.css({ display: 'none', zIndex: 20001 }); this._dialog = element; this._visible = false; this._doorLock = new DoorLock(); this._animation = AlertDialogView._animatorDict[typeof attrs.animation !== 'undefined' ? attrs.animation : 'default']; if (!this._animation) { throw new Error('No such animation: ' + attrs.animation); } this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this)); this._createMask(attrs.maskColor); this._scope.$on('$destroy', this._destroy.bind(this)); }, /** * Show alert dialog. * * @param {Object} [options] * @param {String} [options.animation] animation type * @param {Function} [options.callback] callback after dialog is shown */ show: function(options) { options = options || {}; var cancel = false, callback = options.callback || function() {}; this.emit('preshow', { alertDialog: this, cancel: function() { cancel = true; } }); if (!cancel) { this._doorLock.waitUnlock(function() { var unlock = this._doorLock.lock(), animation = this._animation; this._mask.css('display', 'block'); this._mask.css('opacity', 1); this._element.css('display', 'block'); if (options.animation) { animation = AlertDialogView._animatorDict[options.animation]; } animation.show(this, function() { this._visible = true; unlock(); this.emit('postshow', {alertDialog: this}); callback(); }.bind(this)); }.bind(this)); } }, /** * Hide alert dialog. * * @param {Object} [options] * @param {String} [options.animation] animation type * @param {Function} [options.callback] callback after dialog is hidden */ hide: function(options) { options = options || {}; var cancel = false, callback = options.callback || function() {}; this.emit('prehide', { alertDialog: this, cancel: function() { cancel = true; } }); if (!cancel) { this._doorLock.waitUnlock(function() { var unlock = this._doorLock.lock(), animation = this._animation; if (options.animation) { animation = AlertDialogView._animatorDict[options.animation]; } animation.hide(this, function() { this._element.css('display', 'none'); this._mask.css('display', 'none'); this._visible = false; unlock(); this.emit('posthide', {alertDialog: this}); callback(); }.bind(this)); }.bind(this)); } }, /** * True if alert dialog is visible. * * @return {Boolean} */ isShown: function() { return this._visible; }, /** * Destroy alert dialog. */ destroy: function() { if (this._parentScope) { this._parentScope.$destroy(); this._parentScope = null; } else { this._scope.$destroy(); } }, _destroy: function() { this.emit('destroy'); this._mask.off(); this._element.remove(); this._mask.remove(); this._deviceBackButtonHandler.destroy(); this._deviceBackButtonHandler = this._scope = this._attrs = this._element = this._mask = null; }, /** * Disable or enable alert dialog. * * @param {Boolean} */ setDisabled: function(disabled) { if (typeof disabled !== 'boolean') { throw new Error('Argument must be a boolean.'); } if (disabled) { this._element.attr('disabled', true); } else { this._element.removeAttr('disabled'); } }, /** * True if alert dialog is disabled. * * @return {Boolean} */ isDisabled: function() { return this._element[0].hasAttribute('disabled'); }, /** * Make alert dialog cancelable or uncancelable. * * @param {Boolean} */ setCancelable: function(cancelable) { if (typeof cancelable !== 'boolean') { throw new Error('Argument must be a boolean.'); } if (cancelable) { this._element.attr('cancelable', true); } else { this._element.removeAttr('cancelable'); } }, isCancelable: function() { return this._element[0].hasAttribute('cancelable'); }, _cancel: function() { if (this.isCancelable()) { this.hide({ callback: function () { this.emit('cancel'); }.bind(this) }); } }, _onDeviceBackButton: function(event) { if (this.isCancelable()) { this._cancel.bind(this)(); } else { event.callParentHandler(); } }, _createMask: function(color) { this._mask = angular.element('<div>').addClass('alert-dialog-mask').css({ zIndex: 20000, display: 'none' }); this._mask.on('click', this._cancel.bind(this)); if (color) { this._mask.css('background-color', color); } angular.element(document.body).append(this._mask); } }); AlertDialogView._animatorDict = { 'default': $onsen.isAndroid() ? new AndroidAlertDialogAnimator() : new IOSAlertDialogAnimator(), 'fade': $onsen.isAndroid() ? new AndroidAlertDialogAnimator() : new IOSAlertDialogAnimator(), 'slide': new SlideDialogAnimator(), 'none': new DialogAnimator() }; /** * @param {String} name * @param {DialogAnimator} animator */ AlertDialogView.registerAnimator = function(name, animator) { if (!(animator instanceof DialogAnimator)) { throw new Error('"animator" param must be an instance of DialogAnimator'); } this._animatorDict[name] = animator; }; MicroEvent.mixin(AlertDialogView); return AlertDialogView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('AndroidAlertDialogAnimator', ['DialogAnimator', function(DialogAnimator) { /** * Android style animator for alert dialog. */ var AndroidAlertDialogAnimator = DialogAnimator.extend({ timing: 'cubic-bezier(.1, .7, .4, 1)', duration: 0.2, init: function(options) { options = options || {}; this.timing = options.timing || this.timing; this.duration = options.duration !== undefined ? options.duration : this.duration; }, /** * @param {Object} dialog * @param {Function} callback */ show: function(dialog, callback) { callback = callback ? callback : function() {}; animit.runAll( animit(dialog._mask[0]) .queue({ opacity: 0 }) .queue({ opacity: 1.0 }, { duration: this.duration, timing: this.timing }), animit(dialog._dialog[0]) .queue({ css: { transform: 'translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)', opacity: 0.0 }, duration: 0 }) .queue({ css: { transform: 'translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)', opacity: 1.0 }, duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); }, /** * @param {Object} dialog * @param {Function} callback */ hide: function(dialog, callback) { callback = callback ? callback : function() {}; animit.runAll( animit(dialog._mask[0]) .queue({ opacity: 1.0 }) .queue({ opacity: 0 }, { duration: this.duration, timing: this.timing }), animit(dialog._dialog[0]) .queue({ css: { transform: 'translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)', opacity: 1.0 }, duration: 0 }) .queue({ css: { transform: 'translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)', opacity: 0.0 }, duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); } }); return AndroidAlertDialogAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('AndroidDialogAnimator', ['DialogAnimator', function(DialogAnimator) { /** * Android style animator for dialog. */ var AndroidDialogAnimator = DialogAnimator.extend({ timing: 'ease-in-out', duration: 0.3, init: function(options) { options = options || {}; this.timing = options.timing || this.timing; this.duration = options.duration !== undefined ? options.duration : this.duration; }, /** * @param {Object} dialog * @param {Function} callback */ show: function(dialog, callback) { callback = callback ? callback : function() {}; animit.runAll( animit(dialog._mask[0]) .queue({ opacity: 0 }) .queue({ opacity: 1.0 }, { duration: this.duration, timing: this.timing }), animit(dialog._dialog[0]) .queue({ css: { transform: 'translate3d(-50%, -60%, 0)', opacity: 0.0 }, duration: 0 }) .queue({ css: { transform: 'translate3d(-50%, -50%, 0)', opacity: 1.0 }, duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); }, /** * @param {Object} dialog * @param {Function} callback */ hide: function(dialog, callback) { callback = callback ? callback : function() {}; animit.runAll( animit(dialog._mask[0]) .queue({ opacity: 1.0 }) .queue({ opacity: 0 }, { duration: this.duration, timing: this.timing }), animit(dialog._dialog[0]) .queue({ css: { transform: 'translate3d(-50%, -50%, 0)', opacity: 1.0 }, duration: 0 }) .queue({ css: { transform: 'translate3d(-50%, -60%, 0)', opacity: 0.0 }, duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); } }); return AndroidDialogAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){ 'use strict'; var module = angular.module('onsen'); module.factory('ButtonView', ['$onsen', function($onsen) { var ButtonView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; }, /** * Start spinning. */ startSpin: function() { this._attrs.$set('shouldSpin', 'true'); }, /** * Stop spinning. */ stopSpin: function() { this._attrs.$set('shouldSpin', 'false'); }, /** * Returns whether button is spinning or not. */ isSpinning: function() { return this._attrs.shouldSpin === 'true'; }, /** * Set spin animation. * * @param {String} animation type */ setSpinAnimation: function(animation) { this._scope.$apply(function() { var animations = ['slide-left', 'slide-right', 'slide-up', 'slide-down', 'expand-left', 'expand-right', 'expand-up', 'expand-down', 'zoom-out', 'zoom-in']; if (animations.indexOf(animation) < 0) { console.warn('Animation ' + animation + 'doesn\'t exist.'); animation = 'slide-left'; } this._scope.animation = animation; }.bind(this)); }, /** * Returns whether the button is disabled or not. */ isDisabled: function() { return this._element[0].hasAttribute('disabled'); }, /** * Disabled or enable button. */ setDisabled: function(disabled) { if (typeof disabled !== 'boolean') { throw new Error('Argument must be a boolean.'); } if (disabled) { this._element[0].setAttribute('disabled', ''); } else { this._element[0].removeAttribute('disabled'); } } }); MicroEvent.mixin(ButtonView); return ButtonView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software :qaistributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('CarouselView', ['$onsen', function($onsen) { var VerticalModeTrait = { _getScrollDelta: function(event) { return event.gesture.deltaY; }, _getScrollVelocity: function(event) { return event.gesture.velocityY; }, _getElementSize: function() { if (!this._currentElementSize) { this._currentElementSize = this._element[0].getBoundingClientRect().height; } return this._currentElementSize; }, _generateScrollTransform: function(scroll) { return 'translate3d(0px, ' + -scroll + 'px, 0px)'; }, _layoutCarouselItems: function() { var children = this._getCarouselItemElements(); var sizeAttr = this._getCarouselItemSizeAttr(); var sizeInfo = this._decomposeSizeString(sizeAttr); for (var i = 0; i < children.length; i++) { angular.element(children[i]).css({ position: 'absolute', height: sizeAttr, width: '100%', visibility: 'visible', left: '0px', top: (i * sizeInfo.number) + sizeInfo.unit }); } }, }; var HorizontalModeTrait = { _getScrollDelta: function(event) { return event.gesture.deltaX; }, _getScrollVelocity: function(event) { return event.gesture.velocityX; }, _getElementSize: function() { if (!this._currentElementSize) { this._currentElementSize = this._element[0].getBoundingClientRect().width; } return this._currentElementSize; }, _generateScrollTransform: function(scroll) { return 'translate3d(' + -scroll + 'px, 0px, 0px)'; }, _layoutCarouselItems: function() { var children = this._getCarouselItemElements(); var sizeAttr = this._getCarouselItemSizeAttr(); var sizeInfo = this._decomposeSizeString(sizeAttr); for (var i = 0; i < children.length; i++) { angular.element(children[i]).css({ position: 'absolute', width: sizeAttr, height: '100%', top: '0px', visibility: 'visible', left: (i * sizeInfo.number) + sizeInfo.unit }); } }, }; /** * @class CarouselView */ var CarouselView = Class.extend({ /** * @member jqLite Object */ _element: undefined, /** * @member {Object} */ _scope: undefined, /** * @member {DoorLock} */ _doorLock: undefined, /** * @member {Number} */ _scroll: undefined, /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._doorLock = new DoorLock(); this._scroll = 0; this._lastActiveIndex = 0; this._bindedOnDrag = this._onDrag.bind(this); this._bindedOnDragEnd = this._onDragEnd.bind(this); this._bindedOnResize = this._onResize.bind(this); this._mixin(this._isVertical() ? VerticalModeTrait : HorizontalModeTrait); this._prepareEventListeners(); this._layoutCarouselItems(); this._setupInitialIndex(); this._attrs.$observe('direction', this._onDirectionChange.bind(this)); this._scope.$on('$destroy', this._destroy.bind(this)); this._saveLastState(); }, _onResize: function() { this.refresh(); }, _onDirectionChange: function() { if (this._isVertical()) { this._element.css({ overflowX: 'auto', overflowY: '' }); } else { this._element.css({ overflowX: '', overflowY: 'auto' }); } }, _saveLastState: function() { this._lastState = { elementSize: this._getCarouselItemSize(), carouselElementCount: this._getCarouselItemCount(), width: this._getCarouselItemSize() * this._getCarouselItemCount() }; }, /** * @return {Number} */ _getCarouselItemSize: function() { var sizeAttr = this._getCarouselItemSizeAttr(); var sizeInfo = this._decomposeSizeString(sizeAttr); var elementSize = this._getElementSize(); if (sizeInfo.unit === '%') { return Math.round(sizeInfo.number / 100 * elementSize); } else if (sizeInfo.unit === 'px') { return sizeInfo.number; } else { throw new Error('Invalid state'); } }, /** * @return {Number} */ _getInitialIndex: function() { var index = parseInt(this._element.attr('initial-index'), 10); if (typeof index === 'number' && !isNaN(index)) { return Math.max(Math.min(index, this._getCarouselItemCount() - 1), 0); } else { return 0; } }, /** * @return {String} */ _getCarouselItemSizeAttr: function() { var attrName = 'item-' + (this._isVertical() ? 'height' : 'width'); var itemSizeAttr = ('' + this._element.attr(attrName)).trim(); return itemSizeAttr.match(/^\d+(px|%)$/) ? itemSizeAttr : '100%'; }, /** * @return {Object} */ _decomposeSizeString: function(size) { var matches = size.match(/^(\d+)(px|%)/); return { number: parseInt(matches[1], 10), unit: matches[2], }; }, _setupInitialIndex: function() { this._scroll = this._getCarouselItemSize() * this._getInitialIndex(); this._lastActiveIndex = this._getInitialIndex(); this._scrollTo(this._scroll); }, /** * @param {Boolean} swipeable */ setSwipeable: function(swipeable) { if (swipeable) { this._element[0].setAttribute('swipeable', ''); } else { this._element[0].removeAttribute('swipeable'); } }, /** * @return {Boolean} */ isSwipeable: function() { return this._element[0].hasAttribute('swipeable'); }, /** * @param {Number} ratio */ setAutoScrollRatio: function(ratio) { if (ratio < 0.0 || ratio > 1.0) { throw new Error('Invalid ratio.'); } this._element[0].setAttribute('auto-scroll-ratio', ratio); }, /** * @return {Number} */ getAutoScrollRatio: function(ratio) { var attr = this._element[0].getAttribute('auto-scroll-ratio'); if (!attr) { return 0.5; } var scrollRatio = parseFloat(attr); if (scrollRatio < 0.0 || scrollRatio > 1.0) { throw new Error('Invalid ratio.'); } return isNaN(scrollRatio) ? 0.5 : scrollRatio; }, /** * @param {Number} index * @param {Object} [options] * @param {Function} [options.callback] * @param {String} [options.animation] */ setActiveCarouselItemIndex: function(index, options) { options = options || {}; index = Math.max(0, Math.min(index, this._getCarouselItemCount() - 1)); var scroll = this._getCarouselItemSize() * index; var max = this._calculateMaxScroll(); this._scroll = Math.max(0, Math.min(max, scroll)); this._scrollTo(this._scroll, {animate: options.animation !== 'none', callback: options.callback}); this._tryFirePostChangeEvent(); }, /** * @return {Number} */ getActiveCarouselItemIndex: function() { var scroll = this._scroll; var count = this._getCarouselItemCount(); var size = this._getCarouselItemSize(); if (scroll < 0) { return 0; } for (var i = 0; i < count; i++) { if (size * i <= scroll && size * (i + 1) > scroll) { return i; } } // max carousel index return i; }, /** * @param {Object} [options] * @param {Function} [options.callback] * @param {String} [options.animation] */ next: function(options) { this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex() + 1, options); }, /** * @param {Object} [options] * @param {Function} [options.callback] * @param {String} [options.animation] */ prev: function(options) { this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex() - 1, options); }, /** * @param {Boolean} enabled */ setAutoScrollEnabled: function(enabled) { if (enabled) { this._element[0].setAttribute('auto-scroll', ''); } else { this._element[0].removeAttribute('auto-scroll'); } }, /** * @param {Boolean} enabled */ isAutoScrollEnabled: function(enabled) { return this._element[0].hasAttribute('auto-scroll'); }, /** * @param {Boolean} disabled */ setDisabled: function(disabled) { if (disabled) { this._element[0].setAttribute('disabled', ''); } else { this._element[0].removeAttribute('disabled'); } }, /** * @return {Boolean} */ isDisabled: function() { return this._element[0].hasAttribute('disabled'); }, /** * @param {Boolean} scrollable */ setOverscrollable: function(scrollable) { if (scrollable) { this._element[0].setAttribute('overscrollable', ''); } else { this._element[0].removeAttribute('overscrollable'); } }, /** * @param {Object} trait */ _mixin: function(trait) { Object.keys(trait).forEach(function(key) { this[key] = trait[key]; }.bind(this)); }, /** * @return {Boolean} */ _isEnabledChangeEvent: function() { var elementSize = this._getElementSize(); var carouselItemSize = this._getCarouselItemSize(); return this.isAutoScrollEnabled() && elementSize === carouselItemSize; }, /** * @return {Boolean} */ _isVertical: function() { return this._element.attr('direction') === 'vertical'; }, _prepareEventListeners: function() { this._hammer = new Hammer(this._element[0], { dragMinDistance: 1 }); this._hammer.on('drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown', this._bindedOnDrag); this._hammer.on('dragend', this._bindedOnDragEnd); angular.element(window).on('resize', this._bindedOnResize); }, _tryFirePostChangeEvent: function() { var currentIndex = this.getActiveCarouselItemIndex(); if (this._lastActiveIndex !== currentIndex) { var lastActiveIndex = this._lastActiveIndex; this._lastActiveIndex = currentIndex; this.emit('postchange', { carousel: this, activeIndex: currentIndex, lastActiveIndex: lastActiveIndex }); } }, _onDrag: function(event) { if (!this.isSwipeable()) { return; } var direction = event.gesture.direction; if ((this._isVertical() && (direction === 'left' || direction === 'right')) || (!this._isVertical() && (direction === 'up' || direction === 'down'))) { return; } event.stopPropagation(); this._lastDragEvent = event; var scroll = this._scroll - this._getScrollDelta(event); this._scrollTo(scroll); event.gesture.preventDefault(); this._tryFirePostChangeEvent(); }, _onDragEnd: function(event) { this._currentElementSize = undefined; this._carouselItemElements = undefined; if (!this.isSwipeable()) { return; } this._scroll = this._scroll - this._getScrollDelta(event); if (this._getScrollDelta(event) !== 0) { event.stopPropagation(); } if (this._isOverScroll(this._scroll)) { var waitForAction = false; this.emit('overscroll', { carousel: this, activeIndex: this.getActiveCarouselItemIndex(), direction: this._getOverScrollDirection(), waitToReturn: function(promise) { waitForAction = true; promise.then( function() { this._scrollToKillOverScroll(); }.bind(this) ); }.bind(this) }); if (!waitForAction) { this._scrollToKillOverScroll(); } } else { this._startMomemtumScroll(event); } this._lastDragEvent = null; event.gesture.preventDefault(); }, _getTouchEvents: function() { var EVENTS = [ 'drag', 'dragstart', 'dragend', 'dragup', 'dragdown', 'dragleft', 'dragright', 'swipe', 'swipeup', 'swipedown', 'swipeleft', 'swiperight' ]; return EVENTS.join(' '); }, /** * @return {Boolean} */ isOverscrollable: function() { return this._element[0].hasAttribute('overscrollable'); }, _startMomemtumScroll: function(event) { if (this._lastDragEvent) { var velocity = this._getScrollVelocity(this._lastDragEvent); var duration = 0.3; var scrollDelta = duration * 100 * velocity; var scroll = this._scroll + (this._getScrollDelta(this._lastDragEvent) > 0 ? -scrollDelta : scrollDelta); scroll = this._normalizeScrollPosition(scroll); this._scroll = scroll; animit(this._getCarouselItemElements()) .queue({ transform: this._generateScrollTransform(this._scroll) }, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .queue(function(done) { done(); this._tryFirePostChangeEvent(); }.bind(this)) .play(); } }, _normalizeScrollPosition: function(scroll) { var max = this._calculateMaxScroll(); if (this.isAutoScrollEnabled()) { var arr = []; var size = this._getCarouselItemSize(); for (var i = 0; i < this._getCarouselItemCount(); i++) { if (max >= i * size) { arr.push(i * size); } } arr.push(max); arr.sort(function(left, right) { left = Math.abs(left - scroll); right = Math.abs(right - scroll); return left - right; }); arr = arr.filter(function(item, pos) { return !pos || item != arr[pos - 1]; }); var lastScroll = this._lastActiveIndex * size, scrollRatio = Math.abs(scroll - lastScroll) / size; if (scrollRatio <= this.getAutoScrollRatio()) { return lastScroll; } else if (scrollRatio > this.getAutoScrollRatio() && scrollRatio < 1.0) { if (arr[0] === lastScroll && arr.length > 1) { return arr[1]; } } return arr[0]; } else { return Math.max(0, Math.min(max, scroll)); } }, /** * @return {Array} */ _getCarouselItemElements: function() { var nodeList = this._element[0].children, rv = []; for (var i = nodeList.length; i--; ) { rv.unshift(nodeList[i]); } rv = rv.filter(function(item) { return item.nodeName.toLowerCase() === 'ons-carousel-item'; }); return rv; }, /** * @param {Number} scroll * @param {Object} [options] */ _scrollTo: function(scroll, options) { options = options || {}; var self = this; var isOverscrollable = this.isOverscrollable(); if (options.animate) { animit(this._getCarouselItemElements()) .queue({ transform: this._generateScrollTransform(normalizeScroll(scroll)) }, { duration: 0.3, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .play(options.callback); } else { animit(this._getCarouselItemElements()) .queue({ transform: this._generateScrollTransform(normalizeScroll(scroll)) }) .play(options.callback); } function normalizeScroll(scroll) { var ratio = 0.35; if (scroll < 0) { return isOverscrollable ? Math.round(scroll * ratio) : 0; } var maxScroll = self._calculateMaxScroll(); if (maxScroll < scroll) { return isOverscrollable ? maxScroll + Math.round((scroll - maxScroll) * ratio) : maxScroll; } return scroll; } }, _calculateMaxScroll: function() { var max = this._getCarouselItemCount() * this._getCarouselItemSize() - this._getElementSize(); return Math.ceil(max < 0 ? 0 : max); // Need to return an integer value. }, _isOverScroll: function(scroll) { if (scroll < 0 || scroll > this._calculateMaxScroll()) { return true; } return false; }, _getOverScrollDirection: function() { if (this._isVertical()) { if (this._scroll <= 0) { return 'up'; } else { return 'down'; } } else { if (this._scroll <= 0) { return 'left'; } else { return 'right'; } } }, _scrollToKillOverScroll: function() { var duration = 0.4; if (this._scroll < 0) { animit(this._getCarouselItemElements()) .queue({ transform: this._generateScrollTransform(0) }, { duration: duration, timing: 'cubic-bezier(.1, .4, .1, 1)' }) .play(); this._scroll = 0; return; } var maxScroll = this._calculateMaxScroll(); if (maxScroll < this._scroll) { animit(this._getCarouselItemElements()) .queue({ transform: this._generateScrollTransform(maxScroll) }, { duration: duration, timing: 'cubic-bezier(.1, .4, .1, 1)' }) .play(); this._scroll = maxScroll; return; } return; }, /** * @return {Number} */ _getCarouselItemCount: function() { return this._getCarouselItemElements().length; }, /** * Refresh carousel item layout. */ refresh: function() { // Bug fix if (this._getCarouselItemSize() === 0) { return; } this._mixin(this._isVertical() ? VerticalModeTrait : HorizontalModeTrait); this._layoutCarouselItems(); if (this._lastState && this._lastState.width > 0) { var scroll = this._scroll; if (this._isOverScroll(scroll)) { this._scrollToKillOverScroll(); } else { if (this.isAutoScrollEnabled()) { scroll = this._normalizeScrollPosition(scroll); } this._scrollTo(scroll); } } this._saveLastState(); this.emit('refresh', { carousel: this }); }, /** */ first: function() { this.setActiveCarouselItemIndex(0); }, /** */ last: function() { this.setActiveCarouselItemIndex( Math.max(this._getCarouselItemCount() - 1, 0) ); }, _destroy: function() { this.emit('destroy'); this._hammer.off('drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown', this._bindedOnDrag); this._hammer.off('dragend', this._bindedOnDragEnd); angular.element(window).off('resize', this._bindedOnResize); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(CarouselView); return CarouselView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('DialogView', ['$onsen', 'DialogAnimator', 'IOSDialogAnimator', 'AndroidDialogAnimator', 'SlideDialogAnimator', function($onsen, DialogAnimator, IOSDialogAnimator, AndroidDialogAnimator, SlideDialogAnimator) { var DialogView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs) { this._scope = scope; this._element = element; this._attrs = attrs; this._element.css('display', 'none'); this._dialog = angular.element(element[0].querySelector('.dialog')); this._mask = angular.element(element[0].querySelector('.dialog-mask')); this._dialog.css('z-index', 20001); this._mask.css('z-index', 20000); this._mask.on('click', this._cancel.bind(this)); this._visible = false; this._doorLock = new DoorLock(); this._animation = DialogView._animatorDict[typeof attrs.animation !== 'undefined' ? attrs.animation : 'default']; if (!this._animation) { throw new Error('No such animation: ' + attrs.animation); } this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this)); this._scope.$on('$destroy', this._destroy.bind(this)); }, /** * @return {Object} */ getDeviceBackButtonHandler: function() { return this._deviceBackButtonHandler; }, _getMaskColor: function() { return this._element[0].getAttribute('mask-color') || 'rgba(0, 0, 0, 0.2)'; }, /** * Show dialog. * * @param {Object} [options] * @param {String} [options.animation] animation type * @param {Function} [options.callback] callback after dialog is shown */ show: function(options) { options = options || {}; var cancel = false, callback = options.callback || function() {}; this.emit('preshow', { dialog: this, cancel: function() { cancel = true; } }); if (!cancel) { this._doorLock.waitUnlock(function() { var unlock = this._doorLock.lock(), animation = this._animation; this._element.css('display', 'block'); this._mask.css('opacity', 1); this._mask.css('backgroundColor', this._getMaskColor()); if (options.animation) { animation = DialogView._animatorDict[options.animation]; } animation.show(this, function() { this._visible = true; unlock(); this.emit('postshow', {dialog: this}); callback(); }.bind(this)); }.bind(this)); } }, /** * Hide dialog. * * @param {Object} [options] * @param {String} [options.animation] animation type * @param {Function} [options.callback] callback after dialog is hidden */ hide: function(options) { options = options || {}; var cancel = false, callback = options.callback || function() {}; this.emit('prehide', { dialog: this, cancel: function() { cancel = true; } }); if (!cancel) { this._doorLock.waitUnlock(function() { var unlock = this._doorLock.lock(), animation = this._animation; if (options.animation) { animation = DialogView._animatorDict[options.animation]; } animation.hide(this, function() { this._element.css('display', 'none'); this._visible = false; unlock(); this.emit('posthide', {dialog: this}); callback(); }.bind(this)); }.bind(this)); } }, /** * True if dialog is visible. * * @return {Boolean} */ isShown: function() { return this._visible; }, /** * Destroy dialog. */ destroy: function() { if (this._parentScope) { this._parentScope.$destroy(); this._parentScope = null; } else { this._scope.$destroy(); } }, _destroy: function() { this.emit('destroy'); this._element.remove(); this._deviceBackButtonHandler.destroy(); this._mask.off(); this._deviceBackButtonHandler = this._scope = this._attrs = this._element = this._dialog = this._mask = null; }, /** * Disable or enable dialog. * * @param {Boolean} */ setDisabled: function(disabled) { if (typeof disabled !== 'boolean') { throw new Error('Argument must be a boolean.'); } if (disabled) { this._element.attr('disabled', true); } else { this._element.removeAttr('disabled'); } }, /** * True if dialog is disabled. * * @return {Boolean} */ isDisabled: function() { return this._element[0].hasAttribute('disabled'); }, /** * Make dialog cancelable or uncancelable. * * @param {Boolean} */ setCancelable: function(cancelable) { if (typeof cancelable !== 'boolean') { throw new Error('Argument must be a boolean.'); } if (cancelable) { this._element.attr('cancelable', true); } else { this._element.removeAttr('cancelable'); } }, /** * True if the dialog is cancelable. * * @return {Boolean} */ isCancelable: function() { return this._element[0].hasAttribute('cancelable'); }, _cancel: function() { if (this.isCancelable()) { this.hide({ callback: function () { this.emit('cancel'); }.bind(this) }); } }, _onDeviceBackButton: function(event) { if (this.isCancelable()) { this._cancel.bind(this)(); } else { event.callParentHandler(); } } }); DialogView._animatorDict = { 'default': $onsen.isAndroid() ? new AndroidDialogAnimator() : new IOSDialogAnimator(), 'fade': $onsen.isAndroid() ? new AndroidDialogAnimator() : new IOSDialogAnimator(), 'slide': new SlideDialogAnimator(), 'none': new DialogAnimator() }; /** * @param {String} name * @param {DialogAnimator} animator */ DialogView.registerAnimator = function(name, animator) { if (!(animator instanceof DialogAnimator)) { throw new Error('"animator" param must be an instance of DialogAnimator'); } this._animatorDict[name] = animator; }; MicroEvent.mixin(DialogView); return DialogView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('DialogAnimator', function() { var DialogAnimator = Class.extend({ show: function(dialog, callback) { callback(); }, hide: function(dialog, callback) { callback(); } }); return DialogAnimator; }); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('FadePopoverAnimator', ['PopoverAnimator', function(PopoverAnimator) { /** * Fade animator for popover. */ var FadePopoverAnimator = PopoverAnimator.extend({ timing: 'cubic-bezier(.1, .7, .4, 1)', duration: 0.2, init: function(options) { options = options || {}; this.timing = options.timing || this.timing; this.duration = options.duration !== undefined ? options.duration : this.duration; }, /** * @param {Object} popover * @param {Function} callback */ show: function(popover, callback) { var pop = popover._element[0].querySelector('.popover'), mask = popover._element[0].querySelector('.popover-mask'); animit.runAll( animit(mask) .queue({ opacity: 0 }) .queue({ opacity: 1.0 }, { duration: this.duration, timing: this.timing }), animit(pop) .queue({ transform: 'scale3d(1.3, 1.3, 1.0)', opacity: 0 }) .queue({ transform: 'scale3d(1.0, 1.0, 1.0)', opacity: 1.0 }, { duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); }, /** * @param {Object} popover * @param {Function} callback */ hide: function(popover, callback) { var pop = popover._element[0].querySelector('.popover'), mask = popover._element[0].querySelector('.popover-mask'); animit.runAll( animit(mask) .queue({ opacity: 1.0 }) .queue({ opacity: 0 }, { duration: this.duration, timing: this.timing }), animit(pop) .queue({ opacity: 1.0 }) .queue({ opacity: 0 }, { duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); } }); return FadePopoverAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('FadeTransitionAnimator', ['NavigatorTransitionAnimator', function(NavigatorTransitionAnimator) { /** * Fade-in screen transition. */ var FadeTransitionAnimator = NavigatorTransitionAnimator.extend({ /** * @param {Object} enterPage * @param {Object} leavePage * @param {Function} callback */ push: function(enterPage, leavePage, callback) { animit.runAll( animit([enterPage.getPageView().getContentElement(), enterPage.getPageView().getBackgroundElement()]) .queue({ css: { transform: 'translate3D(0, 0, 0)', opacity: 0 }, duration: 0 }) .queue({ css: { transform: 'translate3D(0, 0, 0)', opacity: 1 }, duration: 0.4, timing: 'linear' }) .resetStyle() .queue(function(done) { callback(); done(); }), animit(enterPage.getPageView().getToolbarElement()) .queue({ css: { transform: 'translate3D(0, 0, 0)', opacity: 0 }, duration: 0 }) .queue({ css: { transform: 'translate3D(0, 0, 0)', opacity: 1 }, duration: 0.4, timing: 'linear' }) .resetStyle() ); }, /** * @param {Object} enterPage * @param {Object} leavePage * @param {Function} done */ pop: function(enterPage, leavePage, callback) { animit.runAll( animit([leavePage.getPageView().getContentElement(), leavePage.getPageView().getBackgroundElement()]) .queue({ css: { transform: 'translate3D(0, 0, 0)', opacity: 1 }, duration: 0 }) .queue({ css: { transform: 'translate3D(0, 0, 0)', opacity: 0 }, duration: 0.4, timing: 'linear' }) .queue(function(done) { callback(); done(); }), animit(leavePage.getPageView().getToolbarElement()) .queue({ css: { transform: 'translate3D(0, 0, 0)', opacity: 1 }, duration: 0 }) .queue({ css: { transform: 'translate3D(0, 0, 0)', opacity: 0 }, duration: 0.4, timing: 'linear' }) ); } }); return FadeTransitionAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){ 'use strict'; var module = angular.module('onsen'); module.factory('GenericView', ['$onsen', function($onsen) { var GenericView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs) { this._element = element; this._scope = scope; } }); MicroEvent.mixin(GenericView); return GenericView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('IOSAlertDialogAnimator', ['DialogAnimator', function(DialogAnimator) { /** * iOS style animator for alert dialog. */ var IOSAlertDialogAnimator = DialogAnimator.extend({ timing: 'cubic-bezier(.1, .7, .4, 1)', duration: 0.2, init: function(options) { options = options || {}; this.timing = options.timing || this.timing; this.duration = options.duration !== undefined ? options.duration : this.duration; }, /** * @param {Object} dialog * @param {Function} callback */ show: function(dialog, callback) { callback = callback ? callback : function() {}; animit.runAll( animit(dialog._mask[0]) .queue({ opacity: 0 }) .queue({ opacity: 1.0 }, { duration: this.duration, timing: this.timing }), animit(dialog._dialog[0]) .queue({ css: { transform: 'translate3d(-50%, -50%, 0) scale3d(1.3, 1.3, 1.0)', opacity: 0.0 }, duration: 0 }) .queue({ css: { transform: 'translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)', opacity: 1.0 }, duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); }, /** * @param {Object} dialog * @param {Function} callback */ hide: function(dialog, callback) { callback = callback ? callback : function() {}; animit.runAll( animit(dialog._mask[0]) .queue({ opacity: 1.0 }) .queue({ opacity: 0 }, { duration: this.duration, timing: this.timing }), animit(dialog._dialog[0]) .queue({ css: { opacity: 1.0 }, duration: 0 }) .queue({ css: { opacity: 0.0 }, duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); } }); return IOSAlertDialogAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('IOSDialogAnimator', ['DialogAnimator', function(DialogAnimator) { /** * iOS style animator for dialog. */ var IOSDialogAnimator = DialogAnimator.extend({ timing: 'ease-in-out', duration: 0.3, init: function(options) { options = options || {}; this.timing = options.timing || this.timing; this.duration = options.duration !== undefined ? options.duration : this.duration; }, /** * @param {Object} dialog * @param {Function} callback */ show: function(dialog, callback) { callback = callback ? callback : function() {}; animit.runAll( animit(dialog._mask[0]) .queue({ opacity: 0 }) .queue({ opacity: 1.0 }, { duration: this.duration, timing: this.timing }), animit(dialog._dialog[0]) .queue({ css: { transform: 'translate3d(-50%, 300%, 0)' }, duration: 0 }) .queue({ css: { transform: 'translate3d(-50%, -50%, 0)' }, duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); }, /** * @param {Object} dialog * @param {Function} callback */ hide: function(dialog, callback) { callback = callback ? callback : function() {}; animit.runAll( animit(dialog._mask[0]) .queue({ opacity: 1.0 }) .queue({ opacity: 0 }, { duration: this.duration, timing: this.timing }), animit(dialog._dialog[0]) .queue({ css: { transform: 'translate3d(-50%, -50%, 0)' }, duration: 0 }) .queue({ css: { transform: 'translate3d(-50%, 300%, 0)' }, duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); } }); return IOSDialogAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('IOSSlideTransitionAnimator', ['NavigatorTransitionAnimator', 'PageView', function(NavigatorTransitionAnimator, PageView) { /** * Slide animator for navigator transition like iOS's screen slide transition. */ var IOSSlideTransitionAnimator = NavigatorTransitionAnimator.extend({ /** Black mask */ backgroundMask : angular.element( '<div style="position: absolute; width: 100%;' + 'height: 100%; background-color: black; opacity: 0;"></div>' ), _decompose: function(page) { var elements = []; var left = page.getPageView().getToolbarLeftItemsElement(); var right = page.getPageView().getToolbarRightItemsElement(); var other = [] .concat(left.children.length === 0 ? left : excludeBackButtonLabel(left.children)) .concat(right.children.length === 0 ? right : excludeBackButtonLabel(right.children)); var pageLabels = [ page.getPageView().getToolbarCenterItemsElement(), page.getPageView().getToolbarBackButtonLabelElement() ]; return { pageLabels: pageLabels, other: other, content: page.getPageView().getContentElement(), background: page.getPageView().getBackgroundElement(), toolbar: page.getPageView().getToolbarElement(), bottomToolbar: page.getPageView().getBottomToolbarElement() }; function excludeBackButtonLabel(elements) { var result = []; for (var i = 0; i < elements.length; i++) { if (elements[i].nodeName.toLowerCase() === 'ons-back-button') { result.push(elements[i].querySelector('.ons-back-button__icon')); } else { result.push(elements[i]); } } return result; } }, _shouldAnimateToolbar: function(enterPage, leavePage) { var bothPageHasToolbar = enterPage.getPageView().hasToolbarElement() && leavePage.getPageView().hasToolbarElement(); var noAndroidLikeToolbar = !angular.element(enterPage.getPageView().getToolbarElement()).hasClass('navigation-bar--android') && !angular.element(leavePage.getPageView().getToolbarElement()).hasClass('navigation-bar--android'); return bothPageHasToolbar && noAndroidLikeToolbar; }, /** * @param {Object} enterPage * @param {Object} leavePage * @param {Function} callback */ push: function(enterPage, leavePage, callback) { var mask = this.backgroundMask.remove(); leavePage.element[0].parentNode.insertBefore(mask[0], leavePage.element[0].nextSibling); var enterPageDecomposition = this._decompose(enterPage); var leavePageDecomposition = this._decompose(leavePage); var delta = (function() { var rect = leavePage.element[0].getBoundingClientRect(); return Math.round(((rect.right - rect.left) / 2) * 0.6); })(); var maskClear = animit(mask[0]) .queue({ opacity: 0, transform: 'translate3d(0, 0, 0)' }) .queue({ opacity: 0.1 }, { duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle() .queue(function(done) { mask.remove(); done(); }); var shouldAnimateToolbar = this._shouldAnimateToolbar(enterPage, leavePage); if (shouldAnimateToolbar) { enterPage.element.css({zIndex: 'auto'}); leavePage.element.css({zIndex: 'auto'}); animit.runAll( maskClear, animit([enterPageDecomposition.content, enterPageDecomposition.bottomToolbar, enterPageDecomposition.background]) .queue({ css: { transform: 'translate3D(100%, 0px, 0px)', }, duration: 0 }) .queue({ css: { transform: 'translate3D(0px, 0px, 0px)', }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle(), animit(enterPageDecomposition.toolbar) .queue({ css: { background: 'none', backgroundColor: 'rgba(0, 0, 0, 0)', borderColor: 'rgba(0, 0, 0, 0)' }, duration: 0 }) .wait(0.3) .resetStyle({ duration: 0.1, transition: 'background-color 0.1s linear, ' + 'border-color 0.1s linear' }), animit(enterPageDecomposition.pageLabels) .queue({ css: { transform: 'translate3d(' + delta + 'px, 0, 0)', opacity: 0 }, duration: 0 }) .queue({ css: { transform: 'translate3d(0, 0, 0)', opacity: 1.0 }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle(), animit(enterPageDecomposition.other) .queue({ css: {opacity: 0}, duration: 0 }) .queue({ css: {opacity: 1}, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle(), animit([leavePageDecomposition.content, leavePageDecomposition.bottomToolbar, leavePageDecomposition.background]) .queue({ css: { transform: 'translate3D(0, 0, 0)', }, duration: 0 }) .queue({ css: { transform: 'translate3D(-25%, 0px, 0px)', }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle() .queue(function(done) { enterPage.element.css({zIndex: ''}); leavePage.element.css({zIndex: ''}); callback(); done(); }), animit(leavePageDecomposition.pageLabels) .queue({ css: { transform: 'translate3d(0, 0, 0)', opacity: 1.0 }, duration: 0 }) .queue({ css: { transform: 'translate3d(-' + delta + 'px, 0, 0)', opacity: 0, }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle(), animit(leavePageDecomposition.other) .queue({ css: {opacity: 1}, duration: 0 }) .queue({ css: {opacity: 0}, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle() ); } else { animit.runAll( maskClear, animit(enterPage.element[0]) .queue({ css: { transform: 'translate3D(100%, 0px, 0px)', }, duration: 0 }) .queue({ css: { transform: 'translate3D(0px, 0px, 0px)', }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle(), animit(leavePage.element[0]) .queue({ css: { transform: 'translate3D(0, 0, 0)' }, duration: 0 }) .queue({ css: { transform: 'translate3D(-25%, 0px, 0px)' }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle() .queue(function(done) { callback(); done(); }) ); } }, /** * @param {Object} enterPage * @param {Object} leavePage * @param {Function} done */ pop: function(enterPage, leavePage, done) { var mask = this.backgroundMask.remove(); enterPage.element[0].parentNode.insertBefore(mask[0], enterPage.element[0].nextSibling); var enterPageDecomposition = this._decompose(enterPage); var leavePageDecomposition = this._decompose(leavePage); var delta = (function() { var rect = leavePage.element[0].getBoundingClientRect(); return Math.round(((rect.right - rect.left) / 2) * 0.6); })(); var maskClear = animit(mask[0]) .queue({ opacity: 0.1, transform: 'translate3d(0, 0, 0)' }) .queue({ opacity: 0 }, { duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle() .queue(function(done) { mask.remove(); done(); }); var shouldAnimateToolbar = this._shouldAnimateToolbar(enterPage, leavePage); if (shouldAnimateToolbar) { enterPage.element.css({zIndex: 'auto'}); leavePage.element.css({zIndex: 'auto'}); animit.runAll( maskClear, animit([enterPageDecomposition.content, enterPageDecomposition.bottomToolbar, enterPageDecomposition.background]) .queue({ css: { transform: 'translate3D(-25%, 0px, 0px)', opacity: 0.9 }, duration: 0 }) .queue({ css: { transform: 'translate3D(0px, 0px, 0px)', opacity: 1.0 }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle(), animit(enterPageDecomposition.pageLabels) .queue({ css: { transform: 'translate3d(-' + delta + 'px, 0, 0)', opacity: 0 }, duration: 0 }) .queue({ css: { transform: 'translate3d(0, 0, 0)', opacity: 1.0 }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle(), animit(enterPageDecomposition.toolbar) .queue({ css: { transform: 'translate3d(0, 0, 0)', opacity: 1.0 }, duration: 0 }) .queue({ css: { transform: 'translate3d(0, 0, 0)', opacity: 1.0 }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle(), animit(enterPageDecomposition.other) .queue({ css: {opacity: 0}, duration: 0 }) .queue({ css: {opacity: 1}, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle(), animit([leavePageDecomposition.content, leavePageDecomposition.bottomToolbar, leavePageDecomposition.background]) .queue({ css: { transform: 'translate3D(0px, 0px, 0px)' }, duration: 0 }) .queue({ css: { transform: 'translate3D(100%, 0px, 0px)' }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .wait(0) .queue(function(finish) { enterPage.element.css({zIndex: ''}); leavePage.element.css({zIndex: ''}); done(); finish(); }), animit(leavePageDecomposition.other) .queue({ css: { transform: 'translate3d(0, 0, 0)', opacity: 1 }, duration: 0 }) .queue({ css: { transform: 'translate3d(0, 0, 0)', opacity: 0, }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }), animit(leavePageDecomposition.toolbar) .queue({ css: { background: 'none', backgroundColor: 'rgba(0, 0, 0, 0)', borderColor: 'rgba(0, 0, 0, 0)' }, duration: 0 }), animit(leavePageDecomposition.pageLabels) .queue({ css: { transform: 'translate3d(0, 0, 0)', opacity: 1.0 }, duration: 0 }) .queue({ css: { transform: 'translate3d(' + delta + 'px, 0, 0)', opacity: 0, }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) ); } else { animit.runAll( maskClear, animit(enterPage.element[0]) .queue({ css: { transform: 'translate3D(-25%, 0px, 0px)', opacity: 0.9 }, duration: 0 }) .queue({ css: { transform: 'translate3D(0px, 0px, 0px)', opacity: 1.0 }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle(), animit(leavePage.element[0]) .queue({ css: { transform: 'translate3D(0px, 0px, 0px)' }, duration: 0 }) .queue({ css: { transform: 'translate3D(100%, 0px, 0px)' }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .queue(function(finish) { done(); finish(); }) ); } } }); return IOSSlideTransitionAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){ 'use strict'; var module = angular.module('onsen'); module.factory('LazyRepeatView', ['$onsen', '$document', '$compile', function($onsen, $document, $compile) { var LazyRepeatView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs, linker) { this._element = element; this._scope = scope; this._attrs = attrs; this._linker = linker; this._parentElement = element.parent(); this._pageContent = this._findPageContent(); if (!this._pageContent) { throw new Error('ons-lazy-repeat must be a descendant of an <ons-page> object.'); } this._itemHeightSum = []; this._maxIndex = 0; this._delegate = this._getDelegate(); this._renderedElements = {}; this._addEventListeners(); this._scope.$watch(this._countItems.bind(this), this._onChange.bind(this)); this._scope.$on('$destroy', this._destroy.bind(this)); this._onChange(); }, _getDelegate: function() { var delegate = this._scope.$eval(this._attrs.onsLazyRepeat); if (typeof delegate === 'undefined') { /*jshint evil:true */ delegate = eval(this._attrs.onsLazyRepeat); } return delegate; }, _countItems: function() { return this._delegate.countItems(); }, _getItemHeight: function(i) { return this._delegate.calculateItemHeight(i); }, _getTopOffset: function() { return this._parentElement[0].getBoundingClientRect().top; }, _render: function() { var items = this._getItemsInView(), keep = {}; this._parentElement.css('height', this._itemHeightSum[this._maxIndex] + 'px'); for (var i = 0, l = items.length; i < l; i ++) { var _item = items[i]; this._renderElement(_item); keep[_item.index] = true; } for (var key in this._renderedElements) { if (this._renderedElements.hasOwnProperty(key) && !keep.hasOwnProperty(key)) { this._removeElement(key); } } }, _isRendered: function(i) { return this._renderedElements.hasOwnProperty(i); }, _renderElement: function(item) { if (this._isRendered(item.index)) { // Update content even if it's already added to DOM // to account for changes within the list. var currentItem = this._renderedElements[item.index]; if (this._delegate.configureItemScope) { this._delegate.configureItemScope(item.index, currentItem.scope); } // Fix position. var element = this._renderedElements[item.index].element; element[0].style.top = item.top + 'px'; return; } var childScope = this._scope.$new(); this._addSpecialProperties(item.index, childScope); this._linker(childScope, function(clone) { if (this._delegate.configureItemScope) { this._delegate.configureItemScope(item.index, childScope); } else if (this._delegate.createItemContent) { clone.append(this._delegate.createItemContent(item.index)); $compile(clone[0].firstChild)(childScope); } this._parentElement.append(clone); clone.css({ position: 'absolute', top: item.top + 'px', left: '0px', right: '0px', display: 'none' }); var element = { element: clone, scope: childScope }; // Don't show elements before they are finished rendering. this._scope.$evalAsync(function() { clone.css('display', 'block'); }); this._renderedElements[item.index] = element; }.bind(this)); }, _removeElement: function(i) { if (!this._isRendered(i)) { return; } var element = this._renderedElements[i]; if (this._delegate.destroyItemScope) { this._delegate.destroyItemScope(i, element.scope); } else if (this._delegate.destroyItemContent) { this._delegate.destroyItemContent(i, element.element.children()[0]); } element.element.remove(); element.scope.$destroy(); element.element = element.scope = null; delete this._renderedElements[i]; }, _removeAllElements: function() { for (var key in this._renderedElements) { if (this._removeElement.hasOwnProperty(key)) { this._removeElement(key); } } }, _calculateStartIndex: function(current) { var start = 0, end = this._maxIndex; // Binary search for index at top of screen so // we can speed up rendering. while (true) { var middle = Math.floor((start + end) / 2), value = current + this._itemHeightSum[middle]; if (end < start) { return 0; } else if (value >= 0 && value - this._getItemHeight(middle) < 0) { return middle; } else if (isNaN(value) || value >= 0) { end = middle - 1; } else { start = middle + 1; } } }, _recalculateItemHeightSum: function() { var sums = this._itemHeightSum; for (var i = 0, sum = 0; i < Math.min(sums.length, this._countItems()); i++) { sum += this._getItemHeight(i); sums[i] = sum; } }, _getItemsInView: function() { var topOffset = this._getTopOffset(), topPosition = topOffset, cnt = this._countItems(); if (cnt !== this._itemCount){ this._recalculateItemHeightSum(); this._maxIndex = cnt - 1; } this._itemCount = cnt; var startIndex = this._calculateStartIndex(topPosition); startIndex = Math.max(startIndex - 30, 0); if (startIndex > 0) { topPosition += this._itemHeightSum[startIndex - 1]; } var items = []; for (var i = startIndex; i < cnt && topPosition < 4 * window.innerHeight; i++) { var h = this._getItemHeight(i); if (i >= this._itemHeightSum.length) { this._itemHeightSum = this._itemHeightSum.concat(new Array(100)); } if (i > 0) { this._itemHeightSum[i] = this._itemHeightSum[i - 1] + h; } else { this._itemHeightSum[i] = h; } this._maxIndex = Math.max(i, this._maxIndex); items.push({ index: i, top: topPosition - topOffset }); topPosition += h; } return items; }, _addSpecialProperties: function(i, scope) { scope.$index = i; scope.$first = i === 0; scope.$last = i === this._countItems() - 1; scope.$middle = !scope.$first && !scope.$last; scope.$even = i % 2 === 0; scope.$odd = !scope.$even; }, _onChange: function() { this._render(); }, _findPageContent: function() { var e = this._element[0]; while(e.parentNode) { e = e.parentNode; if (e.className) { if (e.className.split(/\s+/).indexOf('page__content') >= 0) { break; } } } return e; }, _debounce: function(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) { func.apply(context, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; }, _doubleFireOnTouchend: function(){ this._render(); this._debounce(this._render.bind(this), 100); }, _addEventListeners: function() { if (ons.platform.isIOS()) { this._boundOnChange = this._debounce(this._onChange.bind(this), 30); } else { this._boundOnChange = this._onChange.bind(this); } this._pageContent.addEventListener('scroll', this._boundOnChange, true); if (ons.platform.isIOS()) { this._pageContent.addEventListener('touchmove', this._boundOnChange, true); this._pageContent.addEventListener('touchend', this._doubleFireOnTouchend, true); } $document[0].addEventListener('resize', this._boundOnChange, true); }, _removeEventListeners: function() { this._pageContent.removeEventListener('scroll', this._boundOnChange, true); if (ons.platform.isIOS()) { this._pageContent.removeEventListener('touchmove', this._boundOnChange, true); this._pageContent.removeEventListener('touchend', this._doubleFireOnTouchend, true); } $document[0].removeEventListener('resize', this._boundOnChange, true); }, _destroy: function() { this._removeEventListeners(); this._removeAllElements(); this._parentElement = this._renderedElements = this._element = this._scope = this._attrs = null; } }); return LazyRepeatView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('LiftTransitionAnimator', ['NavigatorTransitionAnimator', function(NavigatorTransitionAnimator) { /** * Lift screen transition. */ var LiftTransitionAnimator = NavigatorTransitionAnimator.extend({ /** Black mask */ backgroundMask : angular.element( '<div style="position: absolute; width: 100%;' + 'height: 100%; background-color: black;"></div>' ), /** * @param {Object} enterPage * @param {Object} leavePage * @param {Function} callback */ push: function(enterPage, leavePage, callback) { var mask = this.backgroundMask.remove(); leavePage.element[0].parentNode.insertBefore(mask[0], leavePage.element[0]); var maskClear = animit(mask[0]) .wait(0.6) .queue(function(done) { mask.remove(); done(); }); animit.runAll( maskClear, animit(enterPage.element[0]) .queue({ css: { transform: 'translate3D(0, 100%, 0)', }, duration: 0 }) .queue({ css: { transform: 'translate3D(0, 0, 0)', }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .wait(0.2) .resetStyle() .queue(function(done) { callback(); done(); }), animit(leavePage.element[0]) .queue({ css: { transform: 'translate3D(0, 0, 0)', opacity: 1.0 }, duration: 0 }) .queue({ css: { transform: 'translate3D(0, -10%, 0)', opacity: 0.9 }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) ); }, /** * @param {Object} enterPage * @param {Object} leavePage * @param {Function} callback */ pop: function(enterPage, leavePage, callback) { var mask = this.backgroundMask.remove(); enterPage.element[0].parentNode.insertBefore(mask[0], enterPage.element[0]); animit.runAll( animit(mask[0]) .wait(0.4) .queue(function(done) { mask.remove(); done(); }), animit(enterPage.element[0]) .queue({ css: { transform: 'translate3D(0, -10%, 0)', opacity: 0.9 }, duration: 0 }) .queue({ css: { transform: 'translate3D(0, 0, 0)', opacity: 1.0 }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .resetStyle() .wait(0.4) .queue(function(done) { callback(); done(); }), animit(leavePage.element[0]) .queue({ css: { transform: 'translate3D(0, 0, 0)' }, duration: 0 }) .queue({ css: { transform: 'translate3D(0, 100%, 0)' }, duration: 0.4, timing: 'cubic-bezier(.1, .7, .1, 1)' }) ); } }); return LiftTransitionAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('ModalView', ['$onsen', '$rootScope', function($onsen, $rootScope) { var ModalView = Class.extend({ _element: undefined, _scope: undefined, /** * @param {Object} scope * @param {jqLite} element */ init: function(scope, element) { this._scope = scope; this._element = element; var pageView = $rootScope.ons.findParentComponentUntil('ons-page', this._element); if (pageView) { this._pageContent = angular.element(pageView._element[0].querySelector('.page__content')); } this._scope.$on('$destroy', this._destroy.bind(this)); this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this)); this.hide(); }, getDeviceBackButtonHandler: function() { return this._deviceBackButtonHandler; }, /** * Show modal view. */ show: function() { this._element.css('display', 'table'); }, _isVisible: function() { return this._element[0].clientWidth > 0; }, _onDeviceBackButton: function() { // Do nothing and stop device-backbutton handler chain. return; }, /** * Hide modal view. */ hide: function() { this._element.css('display', 'none'); }, /** * Toggle modal view visibility. */ toggle: function() { if (this._isVisible()) { return this.hide.apply(this, arguments); } else { return this.show.apply(this, arguments); } }, _destroy: function() { this.emit('destroy', {page: this}); this._deviceBackButtonHandler.destroy(); this._element = this._scope = null; } }); MicroEvent.mixin(ModalView); return ModalView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); var NavigatorPageObject = Class.extend({ /** * @param {Object} params * @param {Object} params.page * @param {Object} params.element * @param {Object} params.pageScope * @param {Object} params.options * @param {Object} params.navigator */ init: function(params) { this.page = params.page; this.name = params.page; this.element = params.element; this.pageScope = params.pageScope; this.options = params.options; this.navigator = params.navigator; // Block events while page is being animated to stop scrolling, pressing buttons, etc. this._blockEvents = function(event) { if (this.navigator._isPopping || this.navigator._isPushing) { event.preventDefault(); event.stopPropagation(); } }.bind(this); this.element.on(this._pointerEvents, this._blockEvents); }, _pointerEvents: 'touchmove', /** * @return {PageView} */ getPageView: function() { if (!this._pageView) { this._pageView = this.element.inheritedData('ons-page'); if (!this._pageView) { throw new Error('Fail to fetch PageView from ons-page element.'); } } return this._pageView; }, destroy: function() { this.pageScope.$destroy(); this.element.off(this._pointerEvents, this._blockEvents); this.element.remove(); this.element = null; this._pageView = null; this.pageScope = null; this.options = null; var index = this.navigator.pages.indexOf(this); if (index !== -1) { this.navigator.pages.splice(index, 1); } this.navigator = null; } }); module.factory('NavigatorView', ['$http', '$parse', '$templateCache', '$compile', '$onsen', '$timeout', 'SimpleSlideTransitionAnimator', 'NavigatorTransitionAnimator', 'LiftTransitionAnimator', 'NullTransitionAnimator', 'IOSSlideTransitionAnimator', 'FadeTransitionAnimator', function($http, $parse, $templateCache, $compile, $onsen, $timeout, SimpleSlideTransitionAnimator, NavigatorTransitionAnimator, LiftTransitionAnimator, NullTransitionAnimator, IOSSlideTransitionAnimator, FadeTransitionAnimator) { /** * Manages the page navigation backed by page stack. * * @class NavigatorView */ var NavigatorView = Class.extend({ /** * @member {jqLite} Object */ _element: undefined, /** * @member {Object} Object */ _attrs: undefined, /** * @member {Array} */ pages: undefined, /** * @member {Object} */ _scope: undefined, /** * @member {DoorLock} */ _doorLock: undefined, /** * @member {Boolean} */ _profiling: false, /** * @param {Object} scope * @param {jqLite} element jqLite Object to manage with navigator * @param {Object} attrs */ init: function(scope, element, attrs) { this._element = element || angular.element(window.document.body); this._scope = scope || this._element.scope(); this._attrs = attrs; this._doorLock = new DoorLock(); this.pages = []; this._isPopping = this._isPushing = false; this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this)); this._scope.$on('$destroy', this._destroy.bind(this)); }, _destroy: function() { this.emit('destroy'); this.pages.forEach(function(page) { page.destroy(); }); this._deviceBackButtonHandler.destroy(); this._deviceBackButtonHandler = null; this._element = this._scope = this._attrs = null; }, _onDeviceBackButton: function(event) { if (this.pages.length > 1) { this._scope.$evalAsync(this.popPage.bind(this)); } else { event.callParentHandler(); } }, /** * @param element jqLite Object * @return jqLite Object */ _normalizePageElement: function(element) { for (var i = 0; i < element.length; i++) { if (element[i].nodeType === 1) { return angular.element(element[i]); } } throw new Error('invalid state'); }, _createPageElementAndLinkFunction : function(templateHTML, pageScope, done) { var div = document.createElement('div'); div.innerHTML = templateHTML.trim(); var pageElement = angular.element(div); var hasPage = div.childElementCount === 1 && div.childNodes[0].nodeName.toLowerCase() === 'ons-page'; if (hasPage) { pageElement = angular.element(div.childNodes[0]); } else { throw new Error('You can not supply no "ons-page" element to "ons-navigator".'); } var link = $compile(pageElement); return { element: pageElement, link: function() { link(pageScope); safeApply(pageScope); } }; function safeApply(scope) { var phase = scope.$root.$$phase; if (phase !== '$apply' && phase !== '$digest') { scope.$apply(); } } }, /** * Insert page object that has the specified pageUrl into the page stack and * if options object is specified, apply the options. * * @param {Number} index * @param {String} page * @param {Object} [options] * @param {String/NavigatorTransitionAnimator} [options.animation] */ insertPage: function(index, page, options) { options = options || {}; if (options && typeof options != 'object') { throw new Error('options must be an object. You supplied ' + options); } if (index === this.pages.length) { return this.pushPage.apply(this, [].slice.call(arguments, 1)); } this._doorLock.waitUnlock(function() { var unlock = this._doorLock.lock(); $onsen.getPageHTMLAsync(page).then(function(templateHTML) { var pageScope = this._createPageScope(); var object = this._createPageElementAndLinkFunction(templateHTML, pageScope); var element = object.element; var link = object.link; element = this._normalizePageElement(element); var pageObject = this._createPageObject(page, element, pageScope, options); if (this.pages.length > 0) { index = normalizeIndex(index); this._element[0].insertBefore(element[0], this.pages[index] ? this.pages[index].element[0] : null); this.pages.splice(index, 0, pageObject); link(); setTimeout(function() { if (this.getCurrentPage() !== pageObject) { element.css('display', 'none'); } unlock(); element = null; }.bind(this), 1000 / 60); } else { this._element.append(element); this.pages.push(pageObject); link(); unlock(); element = null; } }.bind(this), function() { unlock(); throw new Error('Page is not found: ' + page); }); }.bind(this)); var normalizeIndex = function(index) { if (index < 0) { index = this.pages.length + index; } return index; }.bind(this); }, /** * Pushes the specified pageUrl into the page stack and * if options object is specified, apply the options. * * @param {String} page * @param {Object} [options] * @param {String/NavigatorTransitionAnimator} [options.animation] * @param {Function} [options.onTransitionEnd] */ pushPage: function(page, options) { if (this._profiling) { console.time('pushPage'); } options = options || {}; if (options.cancelIfRunning && this._isPushing) { return; } if (options && typeof options != 'object') { throw new Error('options must be an object. You supplied ' + options); } if (this._emitPrePushEvent()) { return; } this._doorLock.waitUnlock(function() { this._pushPage(page, options); }.bind(this)); }, _pushPage: function(page, options) { var unlock = this._doorLock.lock(); var done = function() { unlock(); if (this._profiling) { console.timeEnd('pushPage'); } }; $onsen.getPageHTMLAsync(page).then(function(templateHTML) { var pageScope = this._createPageScope(); var object = this._createPageElementAndLinkFunction(templateHTML, pageScope); setImmediate(function() { this._pushPageDOM(page, object.element, object.link, pageScope, options, done); object = null; }.bind(this)); }.bind(this), function() { done(); throw new Error('Page is not found: ' + page); }.bind(this)); }, getDeviceBackButtonHandler: function() { return this._deviceBackButtonHandler; }, /** * @param {Object} options pushPage()'s options parameter * @param {NavigatorTransitionAnimator} [defaultAnimator] */ _getAnimatorOption: function(options, defaultAnimator) { var animator = null; if (options.animation instanceof NavigatorTransitionAnimator) { return options.animation; } if (typeof options.animation === 'string') { animator = NavigatorView._transitionAnimatorDict[options.animation]; } if (!animator && this._element.attr('animation')) { animator = NavigatorView._transitionAnimatorDict[this._element.attr('animation')]; } if (!animator) { animator = defaultAnimator || NavigatorView._transitionAnimatorDict['default']; } if (!(animator instanceof NavigatorTransitionAnimator)) { throw new Error('"animator" is not an instance of NavigatorTransitionAnimator.'); } return animator; }, _createPageScope: function() { return this._scope.$new(); }, /** * @param {String} page * @param {jqLite} element * @param {Object} pageScope * @param {Object} options */ _createPageObject: function(page, element, pageScope, options) { options.animator = this._getAnimatorOption(options); return new NavigatorPageObject({ page: page, element: element, pageScope: pageScope, options: options, navigator: this }); }, /** * @param {String} page Page name. * @param {Object} element * @param {Function} link * @param {Object} pageScope * @param {Object} options * @param {Function} [unlock] */ _pushPageDOM: function(page, element, link, pageScope, options, unlock) { if (this._profiling) { console.time('pushPageDOM'); } unlock = unlock || function() {}; options = options || {}; element = this._normalizePageElement(element); var pageObject = this._createPageObject(page, element, pageScope, options); var event = { enterPage: pageObject, leavePage: this.pages[this.pages.length - 1], navigator: this }; this.pages.push(pageObject); var done = function() { if (this.pages[this.pages.length - 2]) { this.pages[this.pages.length - 2].element.css('display', 'none'); } if (this._profiling) { console.timeEnd('pushPageDOM'); } this._isPushing = false; unlock(); this.emit('postpush', event); if (typeof options.onTransitionEnd === 'function') { options.onTransitionEnd(); } element = null; }.bind(this); this._isPushing = true; if (this.pages.length > 1) { var leavePage = this.pages.slice(-2)[0]; var enterPage = this.pages.slice(-1)[0]; this._element.append(element); link(); options.animator.push(enterPage, leavePage, done); element = null; } else { this._element.append(element); link(); done(); element = null; } }, /** * @return {Boolean} Whether if event is canceled. */ _emitPrePushEvent: function() { var isCanceled = false; var prePushEvent = { navigator: this, currentPage: this.getCurrentPage(), cancel: function() { isCanceled = true; } }; this.emit('prepush', prePushEvent); return isCanceled; }, /** * @return {Boolean} Whether if event is canceled. */ _emitPrePopEvent: function() { var isCanceled = false; var leavePage = this.getCurrentPage(); var prePopEvent = { navigator: this, currentPage: leavePage, leavePage: leavePage, enterPage: this.pages[this.pages.length - 2], cancel: function() { isCanceled = true; } }; this.emit('prepop', prePopEvent); return isCanceled; }, /** * Pops current page from the page stack. * @param {Object} [options] * @param {Function} [options.onTransitionEnd] */ popPage: function(options) { options = options || {}; if (options.cancelIfRunning && this._isPopping) { return; } this._doorLock.waitUnlock(function() { if (this.pages.length <= 1) { throw new Error('NavigatorView\'s page stack is empty.'); } if (this._emitPrePopEvent()) { return; } this._popPage(options); }.bind(this)); }, _popPage: function(options) { var unlock = this._doorLock.lock(); var leavePage = this.pages.pop(); if (this.pages[this.pages.length - 1]) { this.pages[this.pages.length - 1].element.css('display', 'block'); } var enterPage = this.pages[this.pages.length -1]; var event = { leavePage: leavePage, enterPage: this.pages[this.pages.length - 1], navigator: this }; var callback = function() { leavePage.destroy(); this._isPopping = false; unlock(); this.emit('postpop', event); event.leavePage = null; if (typeof options.onTransitionEnd === 'function') { options.onTransitionEnd(); } }.bind(this); this._isPopping = true; var animator = this._getAnimatorOption(options, leavePage.options.animator); animator.pop(enterPage, leavePage, callback); }, /** * Replaces the current page with the specified one. * * @param {String} page * @param {Object} [options] */ replacePage: function(page, options) { options = options || {}; var onTransitionEnd = options.onTransitionEnd || function() {}; options.onTransitionEnd = function() { if (this.pages.length > 1) { this.pages[this.pages.length - 2].destroy(); } onTransitionEnd(); }.bind(this); this.pushPage(page, options); }, /** * Clears page stack and add the specified pageUrl to the page stack. * If options object is specified, apply the options. * the options object include all the attributes of this navigator. * * @param {String} page * @param {Object} [options] */ resetToPage: function(page, options) { options = options || {}; if (!options.animator && !options.animation) { options.animation = 'none'; } var onTransitionEnd = options.onTransitionEnd || function() {}; var self = this; options.onTransitionEnd = function() { while (self.pages.length > 1) { self.pages.shift().destroy(); } onTransitionEnd(); }; this.pushPage(page, options); }, /** * Get current page's navigator item. * * Use this method to access options passed by pushPage() or resetToPage() method. * eg. ons.navigator.getCurrentPage().options * * @return {Object} */ getCurrentPage: function() { return this.pages[this.pages.length - 1]; }, /** * Retrieve the entire page stages of the navigator. * * @return {Array} */ getPages: function() { return this.pages; }, /** * @return {Boolean} */ canPopPage: function() { return this.pages.length > 1; } }); // Preset transition animators. NavigatorView._transitionAnimatorDict = { 'default': $onsen.isAndroid() ? new SimpleSlideTransitionAnimator() : new IOSSlideTransitionAnimator(), 'slide': $onsen.isAndroid() ? new SimpleSlideTransitionAnimator() : new IOSSlideTransitionAnimator(), 'simpleslide': new SimpleSlideTransitionAnimator(), 'lift': new LiftTransitionAnimator(), 'fade': new FadeTransitionAnimator(), 'none': new NullTransitionAnimator() }; /** * @param {String} name * @param {NavigatorTransitionAnimator} animator */ NavigatorView.registerTransitionAnimator = function(name, animator) { if (!(animator instanceof NavigatorTransitionAnimator)) { throw new Error('"animator" param must be an instance of NavigatorTransitionAnimator'); } this._transitionAnimatorDict[name] = animator; }; MicroEvent.mixin(NavigatorView); return NavigatorView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('NavigatorTransitionAnimator', function() { var NavigatorTransitionAnimator = Class.extend({ push: function(enterPage, leavePage, callback) { callback(); }, pop: function(enterPage, leavePage, callback) { callback(); } }); return NavigatorTransitionAnimator; }); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); /** * Null animator do screen transition with no animations. */ module.factory('NullTransitionAnimator', ['NavigatorTransitionAnimator', function(NavigatorTransitionAnimator) { var NullTransitionAnimator = NavigatorTransitionAnimator.extend({}); return NullTransitionAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('OverlaySlidingMenuAnimator', ['SlidingMenuAnimator', function(SlidingMenuAnimator) { var OverlaySlidingMenuAnimator = SlidingMenuAnimator.extend({ _blackMask: undefined, _isRight: false, _element: false, _menuPage: false, _mainPage: false, _width: false, _duration: false, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function(element, mainPage, menuPage, options) { options = options || {}; this._width = options.width || '90%'; this._isRight = !!options.isRight; this._element = element; this._mainPage = mainPage; this._menuPage = menuPage; this._duration = 0.4; menuPage.css('box-shadow', '0px 0 10px 0px rgba(0, 0, 0, 0.2)'); menuPage.css({ width: options.width, display: 'none', zIndex: 2 }); // Fix for transparent menu page on iOS8. menuPage.css('-webkit-transform', 'translate3d(0px, 0px, 0px)'); mainPage.css({zIndex: 1}); if (this._isRight) { menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { menuPage.css({ right: 'auto', left: '-' + options.width }); } this._blackMask = angular.element('<div></div>').css({ backgroundColor: 'black', top: '0px', left: '0px', right: '0px', bottom: '0px', position: 'absolute', display: 'none', zIndex: 0 }); element.prepend(this._blackMask); }, /** * @param {Object} options * @param {String} options.width */ onResized: function(options) { this._menuPage.css('width', options.width); if (this._isRight) { this._menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { this._menuPage.css({ right: 'auto', left: '-' + options.width }); } if (options.isOpened) { var max = this._menuPage[0].clientWidth; var menuStyle = this._generateMenuPageStyle(max); animit(this._menuPage[0]).queue(menuStyle).play(); } }, /** */ destroy: function() { if (this._blackMask) { this._blackMask.remove(); this._blackMask = null; } this._mainPage.removeAttr('style'); this._menuPage.removeAttr('style'); this._element = this._mainPage = this._menuPage = null; }, /** * @param {Function} callback * @param {Boolean} instant */ openMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this._duration; this._menuPage.css('display', 'block'); this._blackMask.css('display', 'block'); var max = this._menuPage[0].clientWidth; var menuStyle = this._generateMenuPageStyle(max); var mainPageStyle = this._generateMainPageStyle(max); setTimeout(function() { animit(this._mainPage[0]) .queue(mainPageStyle, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .queue(function(done) { callback(); done(); }) .play(); animit(this._menuPage[0]) .queue(menuStyle, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Function} callback * @param {Boolean} instant */ closeMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this._duration; this._blackMask.css({display: 'block'}); var menuPageStyle = this._generateMenuPageStyle(0); var mainPageStyle = this._generateMainPageStyle(0); setTimeout(function() { animit(this._mainPage[0]) .queue(mainPageStyle, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .queue(function(done) { this._menuPage.css('display', 'none'); callback(); done(); }.bind(this)) .play(); animit(this._menuPage[0]) .queue(menuPageStyle, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function(options) { this._menuPage.css('display', 'block'); this._blackMask.css({display: 'block'}); var menuPageStyle = this._generateMenuPageStyle(Math.min(options.maxDistance, options.distance)); var mainPageStyle = this._generateMainPageStyle(Math.min(options.maxDistance, options.distance)); delete mainPageStyle.opacity; animit(this._menuPage[0]) .queue(menuPageStyle) .play(); if (Object.keys(mainPageStyle).length > 0) { animit(this._mainPage[0]) .queue(mainPageStyle) .play(); } }, _generateMenuPageStyle: function(distance) { var max = this._menuPage[0].clientWidth; var x = this._isRight ? -distance : distance; var transform = 'translate3d(' + x + 'px, 0, 0)'; return { transform: transform, 'box-shadow': distance === 0 ? 'none' : '0px 0 10px 0px rgba(0, 0, 0, 0.2)' }; }, _generateMainPageStyle: function(distance) { var max = this._menuPage[0].clientWidth; var opacity = 1 - (0.1 * distance / max); return { opacity: opacity }; }, copy: function() { return new OverlaySlidingMenuAnimator(); } }); return OverlaySlidingMenuAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('PageView', ['$onsen', '$parse', function($onsen, $parse) { var PageView = Class.extend({ _registeredToolbarElement : false, _registeredBottomToolbarElement : false, _nullElement : window.document.createElement('div'), _toolbarElement : null, _bottomToolbarElement : null, init: function(scope, element, attrs) { this._scope = scope; this._element = element; this._attrs = attrs; this._registeredToolbarElement = false; this._registeredBottomToolbarElement = false; this._nullElement = window.document.createElement('div'); this._toolbarElement = angular.element(this._nullElement); this._bottomToolbarElement = angular.element(this._nullElement); this._clearListener = scope.$on('$destroy', this._destroy.bind(this)); this._userDeviceBackButtonListener = angular.noop; if (this._attrs.ngDeviceBackbutton || this._attrs.onDeviceBackbutton) { this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this)); } }, _onDeviceBackButton: function($event) { this._userDeviceBackButtonListener($event); // ng-device-backbutton if (this._attrs.ngDeviceBackbutton) { $parse(this._attrs.ngDeviceBackbutton)(this._scope, {$event: $event}); } // on-device-backbutton /* jshint ignore:start */ if (this._attrs.onDeviceBackbutton) { var lastEvent = window.$event; window.$event = $event; new Function(this._attrs.onDeviceBackbutton)(); window.$event = lastEvent; } /* jshint ignore:end */ }, /** * @param {Function} callback */ setDeviceBackButtonHandler: function(callback) { if (!this._deviceBackButtonHandler) { this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this)); } this._userDeviceBackButtonListener = callback; }, /** * @return {Object/null} */ getDeviceBackButtonHandler: function() { return this._deviceBackButtonHandler || null; }, /** * Register toolbar element to this page. * * @param {jqLite} element */ registerToolbar: function(element) { if (this._registeredToolbarElement) { throw new Error('This page\'s toolbar is already registered.'); } angular.element(this.getContentElement()).attr('no-status-bar-fill', ''); element.remove(); var statusFill = this._element[0].querySelector('.page__status-bar-fill'); if (statusFill) { angular.element(statusFill).after(element); } else { this._element.prepend(element); } this._toolbarElement = element; this._registeredToolbarElement = true; }, /** * Register toolbar element to this page. * * @param {jqLite} element */ registerBottomToolbar: function(element) { if (this._registeredBottomToolbarElement) { throw new Error('This page\'s bottom-toolbar is already registered.'); } element.remove(); this._bottomToolbarElement = element; this._registeredBottomToolbarElement = true; var fill = angular.element(document.createElement('div')); fill.addClass('page__bottom-bar-fill'); fill.css({width: '0px', height: '0px'}); this._element.prepend(fill); this._element.append(element); }, /** * @param {jqLite} element */ registerExtraElement: function(element) { if (!this._extraElement) { this._extraElement = angular.element('<div></div>'); this._extraElement.addClass('page__extra'); this._extraElement.css({ 'z-index': '10001' }); this._element.append(this._extraElement); } this._extraElement.append(element.remove()); }, /** * @return {Boolean} */ hasToolbarElement : function() { return !!this._registeredToolbarElement; }, /** * @return {Boolean} */ hasBottomToolbarElement : function() { return !!this._registeredBottomToolbarElement; }, /** * @return {HTMLElement} */ getContentElement : function() { for (var i = 0; i < this._element.length; i++) { if (this._element[i].querySelector) { var content = this._element[i].querySelector('.page__content'); if (content) { return content; } } } throw Error('fail to get ".page__content" element.'); }, /** * @return {HTMLElement} */ getBackgroundElement : function() { for (var i = 0; i < this._element.length; i++) { if (this._element[i].querySelector) { var content = this._element[i].querySelector('.page__background'); if (content) { return content; } } } throw Error('fail to get ".page__background" element.'); }, /** * @return {HTMLElement} */ getToolbarElement : function() { return this._toolbarElement[0] || this._nullElement; }, /** * @return {HTMLElement} */ getBottomToolbarElement : function() { return this._bottomToolbarElement[0] || this._nullElement; }, /** * @return {HTMLElement} */ getToolbarLeftItemsElement : function() { return this._toolbarElement[0].querySelector('.left') || this._nullElement; }, /** * @return {HTMLElement} */ getToolbarCenterItemsElement : function() { return this._toolbarElement[0].querySelector('.center') || this._nullElement; }, /** * @return {HTMLElement} */ getToolbarRightItemsElement : function() { return this._toolbarElement[0].querySelector('.right') || this._nullElement; }, /** * @return {HTMLElement} */ getToolbarBackButtonLabelElement : function() { return this._toolbarElement[0].querySelector('ons-back-button .back-button__label') || this._nullElement; }, _destroy: function() { this.emit('destroy', {page: this}); if (this._deviceBackButtonHandler) { this._deviceBackButtonHandler.destroy(); this._deviceBackButtonHandler = null; } this._element = null; this._toolbarElement = null; this._nullElement = null; this._bottomToolbarElement = null; this._extraElement = null; this._scope = null; this._clearListener(); } }); MicroEvent.mixin(PageView); return PageView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){ 'use strict'; var module = angular.module('onsen'); module.factory('PopoverView', ['$onsen', 'PopoverAnimator', 'FadePopoverAnimator', function($onsen, PopoverAnimator, FadePopoverAnimator) { var PopoverView = Class.extend({ /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._mask = angular.element(this._element[0].querySelector('.popover-mask')); this._popover = angular.element(this._element[0].querySelector('.popover')); this._mask.css('z-index', 20000); this._popover.css('z-index', 20001); this._element.css('display', 'none'); if (attrs.maskColor) { this._mask.css('background-color', attrs.maskColor); } this._mask.on('click', this._cancel.bind(this)); this._visible = false; this._doorLock = new DoorLock(); this._animation = PopoverView._animatorDict[typeof attrs.animation !== 'undefined' ? attrs.animation : 'fade']; if (!this._animation) { throw new Error('No such animation: ' + attrs.animation); } this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this)); this._onChange = function() { setImmediate(function() { if (this._currentTarget) { this._positionPopover(this._currentTarget); } }.bind(this)); }.bind(this); this._popover[0].addEventListener('DOMNodeInserted', this._onChange, false); this._popover[0].addEventListener('DOMNodeRemoved', this._onChange, false); window.addEventListener('resize', this._onChange, false); this._scope.$on('$destroy', this._destroy.bind(this)); }, _onDeviceBackButton: function(event) { if (this.isCancelable()) { this._cancel.bind(this)(); } else { event.callParentHandler(); } }, _setDirection: function(direction) { if (direction === 'up') { this._scope.direction = direction; this._scope.arrowPosition = 'bottom'; } else if (direction === 'left') { this._scope.direction = direction; this._scope.arrowPosition = 'right'; } else if (direction === 'down') { this._scope.direction = direction; this._scope.arrowPosition = 'top'; } else if (direction == 'right') { this._scope.direction = direction; this._scope.arrowPosition = 'left'; } else { throw new Error('Invalid direction.'); } if (!this._scope.$$phase) { this._scope.$apply(); } }, _positionPopoverByDirection: function(target, direction) { var el = angular.element(this._element[0].querySelector('.popover')), pos = target.getBoundingClientRect(), own = el[0].getBoundingClientRect(), arrow = angular.element(el.children()[1]), offset = 14, margin = 6, radius = parseInt(window.getComputedStyle(el[0].querySelector('.popover__content')).borderRadius); arrow.css({ top: '', left: '' }); // This is the difference between the side and the hypothenuse of the arrow. var diff = (function(x) { return (x / 2) * Math.sqrt(2) - x / 2; })(parseInt(window.getComputedStyle(arrow[0]).width)); // This is the limit for the arrow. If it's moved further than this it's outside the popover. var limit = margin + radius + diff; this._setDirection(direction); // Position popover next to the target. if (['left', 'right'].indexOf(direction) > -1) { if (direction == 'left') { el.css('left', (pos.right - pos.width - own.width - offset) + 'px'); } else { el.css('left', (pos.right + offset) + 'px'); } el.css('top', (pos.bottom - pos.height / 2 - own.height / 2) + 'px'); } else { if (direction == 'up') { el.css('top', (pos.bottom - pos.height - own.height - offset) + 'px'); } else { el.css('top', (pos.bottom + offset) + 'px'); } el.css('left', (pos.right - pos.width / 2 - own.width / 2) + 'px'); } own = el[0].getBoundingClientRect(); // Keep popover inside window and arrow inside popover. if (['left', 'right'].indexOf(direction) > -1) { if (own.top < margin) { arrow.css('top', Math.max(own.height / 2 + own.top - margin, limit) + 'px'); el.css('top', margin + 'px'); } else if (own.bottom > window.innerHeight - margin) { arrow.css('top', Math.min(own.height / 2 - (window.innerHeight - own.bottom) + margin, own.height - limit) + 'px'); el.css('top', (window.innerHeight - own.height - margin) + 'px'); } } else { if (own.left < margin) { arrow.css('left', Math.max(own.width / 2 + own.left - margin, limit) + 'px'); el.css('left', margin + 'px'); } else if (own.right > window.innerWidth - margin) { arrow.css('left', Math.min(own.width / 2 - (window.innerWidth - own.right) + margin, own.width - limit) + 'px'); el.css('left', (window.innerWidth - own.width - margin) + 'px'); } } }, _positionPopover: function(target) { var directions; if (!this._element.attr('direction')) { directions = ['up', 'down', 'left', 'right']; } else { directions = this._element.attr('direction').split(/\s+/); } var position = target.getBoundingClientRect(); // The popover should be placed on the side with the most space. var scores = { left: position.left, right: window.innerWidth - position.right, up: position.top, down: window.innerHeight - position.bottom }; var orderedDirections = Object.keys(scores).sort(function(a, b) {return -(scores[a] - scores[b]);}); for (var i = 0, l = orderedDirections.length; i < l; i++) { var direction = orderedDirections[i]; if (directions.indexOf(direction) > -1) { this._positionPopoverByDirection(target, direction); return; } } }, /** * Show popover. * * @param {HTMLElement} [target] target element * @param {String} [target] css selector * @param {Event} [target] event * @param {Object} [options] options * @param {String} [options.animation] animation type */ show: function(target, options) { if (typeof target === 'string') { target = document.querySelector(target); } else if (target instanceof Event) { target = target.target; } if (!target) { throw new Error('Target undefined'); } options = options || {}; var cancel = false; this.emit('preshow', { popover: this, cancel: function() { cancel = true; } }); if (!cancel) { this._doorLock.waitUnlock(function() { var unlock = this._doorLock.lock(), animation = this._animation; this._element.css('display', 'block'); this._currentTarget = target; this._positionPopover(target); if (options.animation) { animation = PopoverView._animatorDict[options.animation]; } animation.show(this, function() { this._visible = true; this._positionPopover(target); unlock(); this.emit('postshow', {popover: this}); }.bind(this)); }.bind(this)); } }, /** * Hide popover. * * @param {Object} [options] options * @param {String} [options.animation] animation type */ hide: function(options) { options = options || {}; var cancel = false; this.emit('prehide', { popover: this, cancel: function() { cancel = true; } }); if (!cancel) { this._doorLock.waitUnlock(function() { var unlock = this._doorLock.lock(), animation = this._animation; if (options.animation) { animation = PopoverView._animatorDict[options.animation]; } animation.hide(this, function() { this._element.css('display', 'none'); this._visible = false; unlock(); this.emit('posthide', {popover: this}); }.bind(this)); }.bind(this)); } }, /** * Returns whether the popover is visible or not. * * @return {Boolean} */ isShown: function() { return this._visible; }, /** * Destroy the popover and remove it from the DOM tree. */ destroy: function() { if (this._parentScope) { this._parentScope.$destroy(); this._parentScope = null; } else { this._scope.$destroy(); } }, _destroy: function() { this.emit('destroy'); this._deviceBackButtonHandler.destroy(); this._popover[0].removeEventListener('DOMNodeInserted', this._onChange, false); this._popover[0].removeEventListener('DOMNodeRemoved', this._onChange, false); window.removeEventListener('resize', this._onChange, false); this._mask.off(); this._mask.remove(); this._popover.remove(); this._element.remove(); this._onChange = this._deviceBackButtonHandler = this._mask = this._popover = this._element = this._scope = null; }, /** * Set whether the popover should be cancelable or not. * * @param {Boolean} */ setCancelable: function(cancelable) { if (typeof cancelable !== 'boolean') { throw new Error('Argument must be a boolean.'); } if (cancelable) { this._element.attr('cancelable', true); } else { this._element.removeAttr('cancelable'); } }, /** * Return whether the popover is cancelable or not. * * @return {Boolean} */ isCancelable: function() { return this._element[0].hasAttribute('cancelable'); }, _cancel: function() { if (this.isCancelable()) { this.hide(); } }, }); PopoverView._animatorDict = { 'fade': new FadePopoverAnimator(), 'none': new PopoverAnimator() }; /** * @param {String} name * @param {PopoverAnimator} animator */ PopoverView.registerAnimator = function(name, animator) { if (!(animator instanceof PopoverAnimator)) { throw new Error('"animator" param must be an instance of PopoverAnimator'); } this._animatorDict[name] = animator; }; MicroEvent.mixin(PopoverView); return PopoverView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('PopoverAnimator', function() { var PopoverAnimator = Class.extend({ show: function(popover, callback) { callback(); }, hide: function(popover, callback) { callback(); } }); return PopoverAnimator; }); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){ 'use strict'; var module = angular.module('onsen'); module.factory('PullHookView', ['$onsen', '$parse', function($onsen, $parse) { var PullHookView = Class.extend({ STATE_INITIAL: 'initial', STATE_PREACTION: 'preaction', STATE_ACTION: 'action', /** * @param {Object} scope * @param {jqLite} element * @param {Object} attrs */ init: function(scope, element, attrs) { this._element = element; this._scope = scope; this._attrs = attrs; this._scrollElement = this._createScrollElement(); this._pageElement = this._scrollElement.parent(); if (!this._pageElement.hasClass('page__content') && !this._pageElement.hasClass('ons-scroller__content')) { throw new Error('<ons-pull-hook> must be a direct descendant of an <ons-page> or an <ons-scroller> element.'); } this._currentTranslation = 0; this._createEventListeners(); this._setState(this.STATE_INITIAL, true); this._setStyle(); this._scope.$on('$destroy', this._destroy.bind(this)); }, _createScrollElement: function() { var scrollElement = angular.element('<div>') .addClass('scroll'); var pageElement = this._element.parent(), children = pageElement.children(); pageElement.append(scrollElement); scrollElement.append(children); return scrollElement; }, _setStyle: function() { var h = this._getHeight(); this._element.css({ top: '-' + h + 'px', height: h + 'px', lineHeight: h + 'px' }); }, _onScroll: function(event) { var el = this._pageElement[0]; if (el.scrollTop < 0) { el.scrollTop = 0; } }, _generateTranslationTransform: function(scroll) { return 'translate3d(0px, ' + scroll + 'px, 0px)'; }, _onDrag: function(event) { if (this.isDisabled()) { return; } // Ignore when dragging left and right. if (event.gesture.direction === 'left' || event.gesture.direction === 'right') { return; } // Hack to make it work on Android 4.4 WebView. Scrolls manually near the top of the page so // there will be no inertial scroll when scrolling down. Allowing default scrolling will // kill all 'touchmove' events. var el = this._pageElement[0]; el.scrollTop = this._startScroll - event.gesture.deltaY; if (el.scrollTop < window.innerHeight && event.gesture.direction !== 'up') { event.gesture.preventDefault(); } if (this._currentTranslation === 0 && this._getCurrentScroll() === 0) { this._transitionDragLength = event.gesture.deltaY; var direction = event.gesture.interimDirection; if (direction === 'down') { this._transitionDragLength -= 1; } else { this._transitionDragLength += 1; } } var scroll = event.gesture.deltaY - this._startScroll; scroll = Math.max(scroll, 0); if (this._thresholdHeightEnabled() && scroll >= this._getThresholdHeight()) { event.gesture.stopDetect(); setImmediate(function() { this._setState(this.STATE_ACTION); this._translateTo(this._getHeight(), {animate: true}); this._waitForAction(this._onDone.bind(this)); }.bind(this)); } else if (scroll >= this._getHeight()) { this._setState(this.STATE_PREACTION); } else { this._setState(this.STATE_INITIAL); } event.stopPropagation(); this._translateTo(scroll); }, _onDragStart: function(event) { if (this.isDisabled()) { return; } this._startScroll = this._getCurrentScroll(); }, _onDragEnd: function(event) { if (this.isDisabled()) { return; } if (this._currentTranslation > 0) { var scroll = this._currentTranslation; if (scroll > this._getHeight()) { this._setState(this.STATE_ACTION); this._translateTo(this._getHeight(), {animate: true}); this._waitForAction(this._onDone.bind(this)); } else { this._translateTo(0, {animate: true}); } } }, _waitForAction: function(done) { if (this._attrs.ngAction) { this._scope.$eval(this._attrs.ngAction, {$done: done}); } else if (this._attrs.onAction) { /*jshint evil:true */ eval(this._attrs.onAction); } else { done(); } }, _onDone: function(done) { // Check if the pull hook still exists. if (this._element) { this._translateTo(0, {animate: true}); this._setState(this.STATE_INITIAL); } }, _getHeight: function() { return parseInt(this._element[0].getAttribute('height') || '64', 10); }, setHeight: function(height) { this._element[0].setAttribute('height', height + 'px'); this._setStyle(); }, setThresholdHeight: function(thresholdHeight) { this._element[0].setAttribute('threshold-height', thresholdHeight + 'px'); }, _getThresholdHeight: function() { return parseInt(this._element[0].getAttribute('threshold-height') || '96', 10); }, _thresholdHeightEnabled: function() { var th = this._getThresholdHeight(); return th > 0 && th >= this._getHeight(); }, _setState: function(state, noEvent) { var oldState = this._getState(); this._scope.$evalAsync(function() { this._element[0].setAttribute('state', state); if (!noEvent && oldState !== this._getState()) { this.emit('changestate', { state: state, pullHook: this }); } }.bind(this)); }, _getState: function() { return this._element[0].getAttribute('state'); }, getCurrentState: function() { return this._getState(); }, _getCurrentScroll: function() { return this._pageElement[0].scrollTop; }, isDisabled: function() { return this._element[0].hasAttribute('disabled'); }, setDisabled: function(disabled) { if (disabled) { this._element[0].setAttribute('disabled', ''); } else { this._element[0].removeAttribute('disabled'); } }, _translateTo: function(scroll, options) { options = options || {}; this._currentTranslation = scroll; if (options.animate) { animit(this._scrollElement[0]) .queue({ transform: this._generateTranslationTransform(scroll) }, { duration: 0.3, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .play(options.callback); } else { animit(this._scrollElement[0]) .queue({ transform: this._generateTranslationTransform(scroll) }) .play(options.callback); } }, _getMinimumScroll: function() { var scrollHeight = this._scrollElement[0].getBoundingClientRect().height, pageHeight = this._pageElement[0].getBoundingClientRect().height; if (scrollHeight > pageHeight) { return -(scrollHeight - pageHeight); } else { return 0; } }, _createEventListeners: function() { var element = this._scrollElement.parent(); this._hammer = new Hammer(element[0], { dragMinDistance: 1, dragDistanceCorrection: false }); // Event listeners this._bindedOnDrag = this._onDrag.bind(this); this._bindedOnDragStart = this._onDragStart.bind(this); this._bindedOnDragEnd = this._onDragEnd.bind(this); this._bindedOnScroll = this._onScroll.bind(this); // Bind listeners this._hammer.on('drag', this._bindedOnDrag); this._hammer.on('dragstart', this._bindedOnDragStart); this._hammer.on('dragend', this._bindedOnDragEnd); element.on('scroll', this._bindedOnScroll); }, _destroyEventListeners: function() { var element = this._scrollElement.parent(); this._hammer.off('drag', this._bindedOnDrag); this._hammer.off('dragstart', this._bindedOnDragStart); this._hammer.off('dragend', this._bindedOnDragEnd); element.off('scroll', this._bindedOnScroll); }, _destroy: function() { this.emit('destroy'); this._destroyEventListeners(); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(PullHookView); return PullHookView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('PushSlidingMenuAnimator', ['SlidingMenuAnimator', function(SlidingMenuAnimator) { var PushSlidingMenuAnimator = SlidingMenuAnimator.extend({ _isRight: false, _element: undefined, _menuPage: undefined, _mainPage: undefined, _width: undefined, _duration: false, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function(element, mainPage, menuPage, options) { options = options || {}; this._element = element; this._mainPage = mainPage; this._menuPage = menuPage; this._isRight = !!options.isRight; this._width = options.width || '90%'; this._duration = 0.4; menuPage.css({ width: options.width, display: 'none' }); if (this._isRight) { menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { menuPage.css({ right: 'auto', left: '-' + options.width }); } }, /** * @param {Object} options * @param {String} options.width * @param {Object} options.isRight */ onResized: function(options) { this._menuPage.css('width', options.width); if (this._isRight) { this._menuPage.css({ right: '-' + options.width, left: 'auto' }); } else { this._menuPage.css({ right: 'auto', left: '-' + options.width }); } if (options.isOpened) { var max = this._menuPage[0].clientWidth; var mainPageTransform = this._generateAbovePageTransform(max); var menuPageStyle = this._generateBehindPageStyle(max); animit(this._mainPage[0]).queue({transform: mainPageTransform}).play(); animit(this._menuPage[0]).queue(menuPageStyle).play(); } }, /** */ destroy: function() { this._mainPage.removeAttr('style'); this._menuPage.removeAttr('style'); this._element = this._mainPage = this._menuPage = null; }, /** * @param {Function} callback * @param {Boolean} instant */ openMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this._duration; this._menuPage.css('display', 'block'); var max = this._menuPage[0].clientWidth; var aboveTransform = this._generateAbovePageTransform(max); var behindStyle = this._generateBehindPageStyle(max); setTimeout(function() { animit(this._mainPage[0]) .queue({ transform: aboveTransform }, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .queue(function(done) { callback(); done(); }) .play(); animit(this._menuPage[0]) .queue(behindStyle, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Function} callback * @param {Boolean} instant */ closeMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this._duration; var aboveTransform = this._generateAbovePageTransform(0); var behindStyle = this._generateBehindPageStyle(0); setTimeout(function() { animit(this._mainPage[0]) .queue({ transform: aboveTransform }, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .queue({ transform: 'translate3d(0, 0, 0)' }) .queue(function(done) { this._menuPage.css('display', 'none'); callback(); done(); }.bind(this)) .play(); animit(this._menuPage[0]) .queue(behindStyle, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .queue(function(done) { done(); }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function(options) { this._menuPage.css('display', 'block'); var aboveTransform = this._generateAbovePageTransform(Math.min(options.maxDistance, options.distance)); var behindStyle = this._generateBehindPageStyle(Math.min(options.maxDistance, options.distance)); animit(this._mainPage[0]) .queue({transform: aboveTransform}) .play(); animit(this._menuPage[0]) .queue(behindStyle) .play(); }, _generateAbovePageTransform: function(distance) { var x = this._isRight ? -distance : distance; var aboveTransform = 'translate3d(' + x + 'px, 0, 0)'; return aboveTransform; }, _generateBehindPageStyle: function(distance) { var max = this._menuPage[0].clientWidth; var behindX = this._isRight ? -distance : distance; var behindTransform = 'translate3d(' + behindX + 'px, 0, 0)'; return { transform: behindTransform }; }, copy: function() { return new PushSlidingMenuAnimator(); } }); return PushSlidingMenuAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('RevealSlidingMenuAnimator', ['SlidingMenuAnimator', function(SlidingMenuAnimator) { var RevealSlidingMenuAnimator = SlidingMenuAnimator.extend({ _blackMask: undefined, _isRight: false, _menuPage: undefined, _element: undefined, _mainPage: undefined, _duration: undefined, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function(element, mainPage, menuPage, options) { this._element = element; this._menuPage = menuPage; this._mainPage = mainPage; this._isRight = !!options.isRight; this._width = options.width || '90%'; this._duration = 0.4; mainPage.css({ boxShadow: '0px 0 10px 0px rgba(0, 0, 0, 0.2)' }); menuPage.css({ width: options.width, opacity: 0.9, display: 'none' }); if (this._isRight) { menuPage.css({ right: '0px', left: 'auto' }); } else { menuPage.css({ right: 'auto', left: '0px' }); } this._blackMask = angular.element('<div></div>').css({ backgroundColor: 'black', top: '0px', left: '0px', right: '0px', bottom: '0px', position: 'absolute', display: 'none' }); element.prepend(this._blackMask); // Dirty fix for broken rendering bug on android 4.x. animit(mainPage[0]).queue({transform: 'translate3d(0, 0, 0)'}).play(); }, /** * @param {Object} options * @param {Boolean} options.isOpened * @param {String} options.width */ onResized: function(options) { this._width = options.width; this._menuPage.css('width', this._width); if (options.isOpened) { var max = this._menuPage[0].clientWidth; var aboveTransform = this._generateAbovePageTransform(max); var behindStyle = this._generateBehindPageStyle(max); animit(this._mainPage[0]).queue({transform: aboveTransform}).play(); animit(this._menuPage[0]).queue(behindStyle).play(); } }, /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage */ destroy: function() { if (this._blackMask) { this._blackMask.remove(); this._blackMask = null; } if (this._mainPage) { this._mainPage.attr('style', ''); } if (this._menuPage) { this._menuPage.attr('style', ''); } this._mainPage = this._menuPage = this._element = undefined; }, /** * @param {Function} callback * @param {Boolean} instant */ openMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this._duration; this._menuPage.css('display', 'block'); this._blackMask.css('display', 'block'); var max = this._menuPage[0].clientWidth; var aboveTransform = this._generateAbovePageTransform(max); var behindStyle = this._generateBehindPageStyle(max); setTimeout(function() { animit(this._mainPage[0]) .queue({ transform: aboveTransform }, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .queue(function(done) { callback(); done(); }) .play(); animit(this._menuPage[0]) .queue(behindStyle, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Function} callback * @param {Boolean} instant */ closeMenu: function(callback, instant) { var duration = instant === true ? 0.0 : this._duration; this._blackMask.css('display', 'block'); var aboveTransform = this._generateAbovePageTransform(0); var behindStyle = this._generateBehindPageStyle(0); setTimeout(function() { animit(this._mainPage[0]) .queue({ transform: aboveTransform }, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .queue({ transform: 'translate3d(0, 0, 0)' }) .queue(function(done) { this._menuPage.css('display', 'none'); callback(); done(); }.bind(this)) .play(); animit(this._menuPage[0]) .queue(behindStyle, { duration: duration, timing: 'cubic-bezier(.1, .7, .1, 1)' }) .queue(function(done) { done(); }) .play(); }.bind(this), 1000 / 60); }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function(options) { this._menuPage.css('display', 'block'); this._blackMask.css('display', 'block'); var aboveTransform = this._generateAbovePageTransform(Math.min(options.maxDistance, options.distance)); var behindStyle = this._generateBehindPageStyle(Math.min(options.maxDistance, options.distance)); delete behindStyle.opacity; animit(this._mainPage[0]) .queue({transform: aboveTransform}) .play(); animit(this._menuPage[0]) .queue(behindStyle) .play(); }, _generateAbovePageTransform: function(distance) { var x = this._isRight ? -distance : distance; var aboveTransform = 'translate3d(' + x + 'px, 0, 0)'; return aboveTransform; }, _generateBehindPageStyle: function(distance) { var max = this._menuPage[0].getBoundingClientRect().width; var behindDistance = (distance - max) / max * 10; behindDistance = isNaN(behindDistance) ? 0 : Math.max(Math.min(behindDistance, 0), -10); var behindX = this._isRight ? -behindDistance : behindDistance; var behindTransform = 'translate3d(' + behindX + '%, 0, 0)'; var opacity = 1 + behindDistance / 100; return { transform: behindTransform, opacity: opacity }; }, copy: function() { return new RevealSlidingMenuAnimator(); } }); return RevealSlidingMenuAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('SimpleSlideTransitionAnimator', ['NavigatorTransitionAnimator', function(NavigatorTransitionAnimator) { /** * Slide animator for navigator transition. */ var SimpleSlideTransitionAnimator = NavigatorTransitionAnimator.extend({ /** Black mask */ backgroundMask : angular.element( '<div style="z-index: 2; position: absolute; width: 100%;' + 'height: 100%; background-color: black; opacity: 0;"></div>' ), timing: 'cubic-bezier(.1, .7, .4, 1)', duration: 0.3, blackMaskOpacity: 0.4, init: function(options) { options = options || {}; this.timing = options.timing || this.timing; this.duration = options.duration !== undefined ? options.duration : this.duration; }, /** * @param {Object} enterPage * @param {Object} leavePage * @param {Function} callback */ push: function(enterPage, leavePage, callback) { var mask = this.backgroundMask.remove(); leavePage.element[0].parentNode.insertBefore(mask[0], leavePage.element[0].nextSibling); animit.runAll( animit(mask[0]) .queue({ opacity: 0, transform: 'translate3d(0, 0, 0)' }) .queue({ opacity: this.blackMaskOpacity }, { duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { mask.remove(); done(); }), animit(enterPage.element[0]) .queue({ css: { transform: 'translate3D(100%, 0, 0)', }, duration: 0 }) .queue({ css: { transform: 'translate3D(0, 0, 0)', }, duration: this.duration, timing: this.timing }) .resetStyle(), animit(leavePage.element[0]) .queue({ css: { transform: 'translate3D(0, 0, 0)' }, duration: 0 }) .queue({ css: { transform: 'translate3D(-45%, 0px, 0px)' }, duration: this.duration, timing: this.timing }) .resetStyle() .wait(0.2) .queue(function(done) { callback(); done(); }) ); }, /** * @param {Object} enterPage * @param {Object} leavePage * @param {Function} done */ pop: function(enterPage, leavePage, done) { var mask = this.backgroundMask.remove(); enterPage.element[0].parentNode.insertBefore(mask[0], enterPage.element[0].nextSibling); animit.runAll( animit(mask[0]) .queue({ opacity: this.blackMaskOpacity, transform: 'translate3d(0, 0, 0)' }) .queue({ opacity: 0 }, { duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { mask.remove(); done(); }), animit(enterPage.element[0]) .queue({ css: { transform: 'translate3D(-45%, 0px, 0px)', opacity: 0.9 }, duration: 0 }) .queue({ css: { transform: 'translate3D(0px, 0px, 0px)', opacity: 1.0 }, duration: this.duration, timing: this.timing }) .resetStyle(), animit(leavePage.element[0]) .queue({ css: { transform: 'translate3D(0px, 0px, 0px)' }, duration: 0 }) .queue({ css: { transform: 'translate3D(100%, 0px, 0px)' }, duration: this.duration, timing: this.timing }) .wait(0.2) .queue(function(finish) { done(); finish(); }) ); } }); return SimpleSlideTransitionAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('SlideDialogAnimator', ['DialogAnimator', function(DialogAnimator) { /** * Slide animator for dialog. */ var SlideDialogAnimator = DialogAnimator.extend({ timing: 'cubic-bezier(.1, .7, .4, 1)', duration: 0.2, init: function(options) { options = options || {}; this.timing = options.timing || this.timing; this.duration = options.duration !== undefined ? options.duration : this.duration; }, /** * @param {Object} dialog * @param {Function} callback */ show: function(dialog, callback) { callback = callback ? callback : function() {}; animit.runAll( animit(dialog._mask[0]) .queue({ opacity: 0 }) .queue({ opacity: 1.0 }, { duration: this.duration, timing: this.timing }), animit(dialog._dialog[0]) .queue({ css: { transform: 'translate3D(-50%, -350%, 0)', }, duration: 0 }) .queue({ css: { transform: 'translate3D(-50%, -50%, 0)', }, duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); }, /** * @param {Object} dialog * @param {Function} callback */ hide: function(dialog, callback) { callback = callback ? callback : function() {}; animit.runAll( animit(dialog._mask[0]) .queue({ opacity: 1.0 }) .queue({ opacity: 0 }, { duration: this.duration, timing: this.timing }), animit(dialog._dialog[0]) .queue({ css: { transform: 'translate3D(-50%, -50%, 0)' }, duration: 0 }) .queue({ css: { transform: 'translate3D(-50%, -350%, 0)' }, duration: this.duration, timing: this.timing }) .resetStyle() .queue(function(done) { callback(); done(); }) ); } }); return SlideDialogAnimator; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var module = angular.module('onsen'); var SlidingMenuViewModel = Class.extend({ /** * @member Number */ _distance: 0, /** * @member Number */ _maxDistance: undefined, /** * @param {Object} options * @param {Number} maxDistance */ init: function(options) { if (!angular.isNumber(options.maxDistance)) { throw new Error('options.maxDistance must be number'); } this.setMaxDistance(options.maxDistance); }, /** * @param {Number} maxDistance */ setMaxDistance: function(maxDistance) { if (maxDistance <= 0) { throw new Error('maxDistance must be greater then zero.'); } if (this.isOpened()) { this._distance = maxDistance; } this._maxDistance = maxDistance; }, /** * @return {Boolean} */ shouldOpen: function() { return !this.isOpened() && this._distance >= this._maxDistance / 2; }, /** * @return {Boolean} */ shouldClose: function() { return !this.isClosed() && this._distance < this._maxDistance / 2; }, openOrClose: function(options) { if (this.shouldOpen()) { this.open(options); } else if (this.shouldClose()) { this.close(options); } }, close: function(options) { var callback = options.callback || function() {}; if (!this.isClosed()) { this._distance = 0; this.emit('close', options); } else { callback(); } }, open: function(options) { var callback = options.callback || function() {}; if (!this.isOpened()) { this._distance = this._maxDistance; this.emit('open', options); } else { callback(); } }, /** * @return {Boolean} */ isClosed: function() { return this._distance === 0; }, /** * @return {Boolean} */ isOpened: function() { return this._distance === this._maxDistance; }, /** * @return {Number} */ getX: function() { return this._distance; }, /** * @return {Number} */ getMaxDistance: function() { return this._maxDistance; }, /** * @param {Number} x */ translate: function(x) { this._distance = Math.max(1, Math.min(this._maxDistance - 1, x)); var options = { distance: this._distance, maxDistance: this._maxDistance }; this.emit('translate', options); }, toggle: function() { if (this.isClosed()) { this.open(); } else { this.close(); } } }); MicroEvent.mixin(SlidingMenuViewModel); module.factory('SlidingMenuView', ['$onsen', '$compile', 'SlidingMenuAnimator', 'RevealSlidingMenuAnimator', 'PushSlidingMenuAnimator', 'OverlaySlidingMenuAnimator', function($onsen, $compile, SlidingMenuAnimator, RevealSlidingMenuAnimator, PushSlidingMenuAnimator, OverlaySlidingMenuAnimator) { var SlidingMenuView = Class.extend({ _scope: undefined, _attrs: undefined, _element: undefined, _menuPage: undefined, _mainPage: undefined, _doorLock: undefined, _isRightMenu: false, init: function(scope, element, attrs) { this._scope = scope; this._attrs = attrs; this._element = element; this._menuPage = angular.element(element[0].querySelector('.onsen-sliding-menu__menu')); this._mainPage = angular.element(element[0].querySelector('.onsen-sliding-menu__main')); this._doorLock = new DoorLock(); this._isRightMenu = attrs.side === 'right'; // Close menu on tap event. this._mainPageHammer = new Hammer(this._mainPage[0]); this._bindedOnTap = this._onTap.bind(this); var maxDistance = this._normalizeMaxSlideDistanceAttr(); this._logic = new SlidingMenuViewModel({maxDistance: Math.max(maxDistance, 1)}); this._logic.on('translate', this._translate.bind(this)); this._logic.on('open', function(options) { this._open(options); }.bind(this)); this._logic.on('close', function(options) { this._close(options); }.bind(this)); attrs.$observe('maxSlideDistance', this._onMaxSlideDistanceChanged.bind(this)); attrs.$observe('swipeable', this._onSwipeableChanged.bind(this)); this._bindedOnWindowResize = this._onWindowResize.bind(this); window.addEventListener('resize', this._bindedOnWindowResize); this._boundHandleEvent = this._handleEvent.bind(this); this._bindEvents(); if (attrs.mainPage) { this.setMainPage(attrs.mainPage); } if (attrs.menuPage) { this.setMenuPage(attrs.menuPage); } this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this)); var unlock = this._doorLock.lock(); window.setTimeout(function() { var maxDistance = this._normalizeMaxSlideDistanceAttr(); this._logic.setMaxDistance(maxDistance); this._menuPage.css({opacity: 1}); this._animator = this._getAnimatorOption(); this._animator.setup( this._element, this._mainPage, this._menuPage, { isRight: this._isRightMenu, width: this._attrs.maxSlideDistance || '90%' } ); unlock(); }.bind(this), 400); scope.$on('$destroy', this._destroy.bind(this)); if (!attrs.swipeable) { this.setSwipeable(true); } }, getDeviceBackButtonHandler: function() { return this._deviceBackButtonHandler; }, _onDeviceBackButton: function(event) { if (this.isMenuOpened()) { this.closeMenu(); } else { event.callParentHandler(); } }, _onTap: function() { if (this.isMenuOpened()) { this.closeMenu(); } }, _refreshMenuPageWidth: function() { var width = ('maxSlideDistance' in this._attrs) ? this._attrs.maxSlideDistance : '90%'; if (this._animator) { this._animator.onResized({ isOpened: this._logic.isOpened(), width: width }); } }, _destroy: function() { this.emit('destroy'); this._deviceBackButtonHandler.destroy(); window.removeEventListener('resize', this._bindedOnWindowResize); this._mainPageHammer.off('tap', this._bindedOnTap); this._element = this._scope = this._attrs = null; }, _getAnimatorOption: function() { var animator = SlidingMenuView._animatorDict[this._attrs.type]; if (!(animator instanceof SlidingMenuAnimator)) { animator = SlidingMenuView._animatorDict['default']; } return animator.copy(); }, _onSwipeableChanged: function(swipeable) { swipeable = swipeable === '' || swipeable === undefined || swipeable == 'true'; this.setSwipeable(swipeable); }, /** * @param {Boolean} enabled */ setSwipeable: function(enabled) { if (enabled) { this._activateHammer(); } else { this._deactivateHammer(); } }, _onWindowResize: function() { this._recalculateMAX(); this._refreshMenuPageWidth(); }, _onMaxSlideDistanceChanged: function() { this._recalculateMAX(); this._refreshMenuPageWidth(); }, /** * @return {Number} */ _normalizeMaxSlideDistanceAttr: function() { var maxDistance = this._attrs.maxSlideDistance; if (!('maxSlideDistance' in this._attrs)) { maxDistance = 0.9 * this._mainPage[0].clientWidth; } else if (typeof maxDistance == 'string') { if (maxDistance.indexOf('px', maxDistance.length - 2) !== -1) { maxDistance = parseInt(maxDistance.replace('px', ''), 10); } else if (maxDistance.indexOf('%', maxDistance.length - 1) > 0) { maxDistance = maxDistance.replace('%', ''); maxDistance = parseFloat(maxDistance) / 100 * this._mainPage[0].clientWidth; } } else { throw new Error('invalid state'); } return maxDistance; }, _recalculateMAX: function() { var maxDistance = this._normalizeMaxSlideDistanceAttr(); if (maxDistance) { this._logic.setMaxDistance(parseInt(maxDistance, 10)); } }, _activateHammer: function(){ this._hammertime.on('touch dragleft dragright swipeleft swiperight release', this._boundHandleEvent); }, _deactivateHammer: function(){ this._hammertime.off('touch dragleft dragright swipeleft swiperight release', this._boundHandleEvent); }, _bindEvents: function() { this._hammertime = new Hammer(this._element[0], { dragMinDistance: 1 }); }, _appendMainPage: function(pageUrl, templateHTML) { var pageScope = this._scope.$new(); var pageContent = angular.element(templateHTML); var link = $compile(pageContent); this._mainPage.append(pageContent); if (this._currentPageElement) { this._currentPageElement.remove(); this._currentPageScope.$destroy(); } link(pageScope); this._currentPageElement = pageContent; this._currentPageScope = pageScope; this._currentPageUrl = pageUrl; }, /** * @param {String} */ _appendMenuPage: function(templateHTML) { var pageScope = this._scope.$new(); var pageContent = angular.element(templateHTML); var link = $compile(pageContent); this._menuPage.append(pageContent); if (this._currentMenuPageScope) { this._currentMenuPageScope.$destroy(); this._currentMenuPageElement.remove(); } link(pageScope); this._currentMenuPageElement = pageContent; this._currentMenuPageScope = pageScope; }, /** * @param {String} page * @param {Object} options * @param {Boolean} [options.closeMenu] * @param {Boolean} [options.callback] */ setMenuPage: function(page, options) { if (page) { options = options || {}; options.callback = options.callback || function() {}; var self = this; $onsen.getPageHTMLAsync(page).then(function(html) { self._appendMenuPage(angular.element(html)); if (options.closeMenu) { self.close(); } options.callback(); }, function() { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, /** * @param {String} pageUrl * @param {Object} options * @param {Boolean} [options.closeMenu] * @param {Boolean} [options.callback] */ setMainPage: function(pageUrl, options) { options = options || {}; options.callback = options.callback || function() {}; var done = function() { if (options.closeMenu) { this.close(); } options.callback(); }.bind(this); if (this.currentPageUrl === pageUrl) { done(); return; } if (pageUrl) { var self = this; $onsen.getPageHTMLAsync(pageUrl).then(function(html) { self._appendMainPage(pageUrl, html); done(); }, function() { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, _handleEvent: function(event) { if (this._doorLock.isLocked()) { return; } if (this._isInsideIgnoredElement(event.target)){ event.gesture.stopDetect(); } switch (event.type) { case 'dragleft': case 'dragright': if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) { return; } event.gesture.preventDefault(); var deltaX = event.gesture.deltaX; var deltaDistance = this._isRightMenu ? -deltaX : deltaX; var startEvent = event.gesture.startEvent; if (!('isOpened' in startEvent)) { startEvent.isOpened = this._logic.isOpened(); } if (deltaDistance < 0 && this._logic.isClosed()) { break; } if (deltaDistance > 0 && this._logic.isOpened()) { break; } var distance = startEvent.isOpened ? deltaDistance + this._logic.getMaxDistance() : deltaDistance; this._logic.translate(distance); break; case 'swipeleft': event.gesture.preventDefault(); if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) { return; } if (this._isRightMenu) { this.open(); } else { this.close(); } event.gesture.stopDetect(); break; case 'swiperight': event.gesture.preventDefault(); if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) { return; } if (this._isRightMenu) { this.close(); } else { this.open(); } event.gesture.stopDetect(); break; case 'release': this._lastDistance = null; if (this._logic.shouldOpen()) { this.open(); } else if (this._logic.shouldClose()) { this.close(); } break; } }, /** * @param {jqLite} element * @return {Boolean} */ _isInsideIgnoredElement: function(element) { do { if (element.getAttribute && element.getAttribute('sliding-menu-ignore')) { return true; } element = element.parentNode; } while (element); return false; }, _isInsideSwipeTargetArea: function(event) { var x = event.gesture.center.pageX; if (!('_swipeTargetWidth' in event.gesture.startEvent)) { event.gesture.startEvent._swipeTargetWidth = this._getSwipeTargetWidth(); } var targetWidth = event.gesture.startEvent._swipeTargetWidth; return this._isRightMenu ? this._mainPage[0].clientWidth - x < targetWidth : x < targetWidth; }, _getSwipeTargetWidth: function() { var targetWidth = this._attrs.swipeTargetWidth; if (typeof targetWidth == 'string') { targetWidth = targetWidth.replace('px', ''); } var width = parseInt(targetWidth, 10); if (width < 0 || !targetWidth) { return this._mainPage[0].clientWidth; } else { return width; } }, closeMenu: function() { return this.close.apply(this, arguments); }, /** * Close sliding-menu page. * * @param {Object} options */ close: function(options) { options = options || {}; options = typeof options == 'function' ? {callback: options} : options; if (!this._logic.isClosed()) { this.emit('preclose', { slidingMenu: this }); this._doorLock.waitUnlock(function() { this._logic.close(options); }.bind(this)); } }, _close: function(options) { var callback = options.callback || function() {}, unlock = this._doorLock.lock(), instant = options.animation == 'none'; this._animator.closeMenu(function() { unlock(); this._mainPage.children().css('pointer-events', ''); this._mainPageHammer.off('tap', this._bindedOnTap); this.emit('postclose', { slidingMenu: this }); callback(); }.bind(this), instant); }, /** * Open sliding-menu page. * * @param {Object} [options] * @param {Function} [options.callback] */ openMenu: function() { return this.open.apply(this, arguments); }, /** * Open sliding-menu page. * * @param {Object} [options] * @param {Function} [options.callback] */ open: function(options) { options = options || {}; options = typeof options == 'function' ? {callback: options} : options; this.emit('preopen', { slidingMenu: this }); this._doorLock.waitUnlock(function() { this._logic.open(options); }.bind(this)); }, _open: function(options) { var callback = options.callback || function() {}, unlock = this._doorLock.lock(), instant = options.animation == 'none'; this._animator.openMenu(function() { unlock(); this._mainPage.children().css('pointer-events', 'none'); this._mainPageHammer.on('tap', this._bindedOnTap); this.emit('postopen', { slidingMenu: this }); callback(); }.bind(this), instant); }, /** * Toggle sliding-menu page. * @param {Object} [options] * @param {Function} [options.callback] */ toggle: function(options) { if (this._logic.isClosed()) { this.open(options); } else { this.close(options); } }, /** * Toggle sliding-menu page. */ toggleMenu: function() { return this.toggle.apply(this, arguments); }, /** * @return {Boolean} */ isMenuOpened: function() { return this._logic.isOpened(); }, /** * @param {Object} event */ _translate: function(event) { this._animator.translateMenu(event); } }); // Preset sliding menu animators. SlidingMenuView._animatorDict = { 'default': new RevealSlidingMenuAnimator(), 'overlay': new OverlaySlidingMenuAnimator(), 'reveal': new RevealSlidingMenuAnimator(), 'push': new PushSlidingMenuAnimator() }; /** * @param {String} name * @param {NavigatorTransitionAnimator} animator */ SlidingMenuView.registerSlidingMenuAnimator = function(name, animator) { if (!(animator instanceof SlidingMenuAnimator)) { throw new Error('"animator" param must be an instance of SlidingMenuAnimator'); } this._animatorDict[name] = animator; }; MicroEvent.mixin(SlidingMenuView); return SlidingMenuView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('SlidingMenuAnimator', function() { return Class.extend({ /** * @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element * @param {jqLite} mainPage * @param {jqLite} menuPage * @param {Object} options * @param {String} options.width "width" style value * @param {Boolean} options.isRight */ setup: function(element, mainPage, menuPage, options) { }, /** * @param {Object} options * @param {Boolean} options.isRight * @param {Boolean} options.isOpened * @param {String} options.width */ onResized: function(options) { }, /** * @param {Function} callback */ openMenu: function(callback) { }, /** * @param {Function} callback */ closeClose: function(callback) { }, /** */ destroy: function() { }, /** * @param {Object} options * @param {Number} options.distance * @param {Number} options.maxDistance */ translateMenu: function(mainPage, menuPage, options) { }, /** * @return {SlidingMenuAnimator} */ copy: function() { throw new Error('Override copy method.'); } }); }); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict'; var module = angular.module('onsen'); module.factory('SplitView', ['$compile', 'RevealSlidingMenuAnimator', '$onsen', '$onsGlobal', function($compile, RevealSlidingMenuAnimator, $onsen, $onsGlobal) { var SPLIT_MODE = 0; var COLLAPSE_MODE = 1; var MAIN_PAGE_RATIO = 0.9; var ON_PAGE_READY = 'onPageReady'; var SplitView = Class.extend({ init: function(scope, element, attrs) { element.addClass('onsen-sliding-menu'); this._element = element; this._scope = scope; this._attrs = attrs; this._mainPage = angular.element(element[0].querySelector('.onsen-split-view__main')); this._secondaryPage = angular.element(element[0].querySelector('.onsen-split-view__secondary')); this._max = this._mainPage[0].clientWidth * MAIN_PAGE_RATIO; this._mode = SPLIT_MODE; this._doorLock = new DoorLock(); this._doSplit = false; this._doCollapse = false; $onsGlobal.orientation.on('change', this._onResize.bind(this)); this._animator = new RevealSlidingMenuAnimator(); this._element.css('display', 'none'); if (attrs.mainPage) { this.setMainPage(attrs.mainPage); } if (attrs.secondaryPage) { this.setSecondaryPage(attrs.secondaryPage); } var unlock = this._doorLock.lock(); this._considerChangingCollapse(); this._setSize(); setTimeout(function() { this._element.css('display', 'block'); unlock(); }.bind(this), 1000 / 60 * 2); scope.$on('$destroy', this._destroy.bind(this)); }, /** * @param {String} templateHTML */ _appendSecondPage: function(templateHTML) { var pageScope = this._scope.$new(); var pageContent = $compile(templateHTML)(pageScope); this._secondaryPage.append(pageContent); if (this._currentSecondaryPageElement) { this._currentSecondaryPageElement.remove(); this._currentSecondaryPageScope.$destroy(); } this._currentSecondaryPageElement = pageContent; this._currentSecondaryPageScope = pageScope; }, /** * @param {String} templateHTML */ _appendMainPage: function(templateHTML) { var pageScope = this._scope.$new(); var pageContent = $compile(templateHTML)(pageScope); this._mainPage.append(pageContent); if (this._currentPage) { this._currentPage.remove(); this._currentPageScope.$destroy(); } this._currentPage = pageContent; this._currentPageScope = pageScope; }, /** * @param {String} page */ setSecondaryPage : function(page) { if (page) { $onsen.getPageHTMLAsync(page).then(function(html) { this._appendSecondPage(angular.element(html.trim())); }.bind(this), function() { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, /** * @param {String} page */ setMainPage : function(page) { if (page) { $onsen.getPageHTMLAsync(page).then(function(html) { this._appendMainPage(angular.element(html.trim())); }.bind(this), function() { throw new Error('Page is not found: ' + page); }); } else { throw new Error('cannot set undefined page'); } }, _onResize: function() { var lastMode = this._mode; this._considerChangingCollapse(); if (lastMode === COLLAPSE_MODE && this._mode === COLLAPSE_MODE) { this._animator.onResized({ isOpened: false, width: '90%' }); } this._max = this._mainPage[0].clientWidth * MAIN_PAGE_RATIO; }, _considerChangingCollapse: function() { var should = this._shouldCollapse(); if (should && this._mode !== COLLAPSE_MODE) { this._fireUpdateEvent(); if (this._doSplit) { this._activateSplitMode(); } else { this._activateCollapseMode(); } } else if (!should && this._mode === COLLAPSE_MODE) { this._fireUpdateEvent(); if (this._doCollapse) { this._activateCollapseMode(); } else { this._activateSplitMode(); } } this._doCollapse = this._doSplit = false; }, update: function() { this._fireUpdateEvent(); var should = this._shouldCollapse(); if (this._doSplit) { this._activateSplitMode(); } else if (this._doCollapse) { this._activateCollapseMode(); } else if (should) { this._activateCollapseMode(); } else if (!should) { this._activateSplitMode(); } this._doSplit = this._doCollapse = false; }, _getOrientation: function() { if ($onsGlobal.orientation.isPortrait()) { return 'portrait'; } else { return 'landscape'; } }, getCurrentMode: function() { if (this._mode === COLLAPSE_MODE) { return 'collapse'; } else { return 'split'; } }, _shouldCollapse: function() { var c = 'portrait'; if (typeof this._attrs.collapse === 'string') { c = this._attrs.collapse.trim(); } if (c == 'portrait') { return $onsGlobal.orientation.isPortrait(); } else if (c == 'landscape') { return $onsGlobal.orientation.isLandscape(); } else if (c.substr(0,5) == 'width') { var num = c.split(' ')[1]; if (num.indexOf('px') >= 0) { num = num.substr(0,num.length-2); } var width = window.innerWidth; return isNumber(num) && width < num; } else { var mq = window.matchMedia(c); return mq.matches; } }, _setSize: function() { if (this._mode === SPLIT_MODE) { if (!this._attrs.mainPageWidth) { this._attrs.mainPageWidth = '70'; } var secondarySize = 100 - this._attrs.mainPageWidth.replace('%', ''); this._secondaryPage.css({ width: secondarySize + '%', opacity: 1 }); this._mainPage.css({ width: this._attrs.mainPageWidth + '%' }); this._mainPage.css('left', secondarySize + '%'); } }, _fireEvent: function(name) { this.emit(name, { splitView: this, width: window.innerWidth, orientation: this._getOrientation() }); }, _fireUpdateEvent: function() { var that = this; this.emit('update', { splitView: this, shouldCollapse: this._shouldCollapse(), currentMode: this.getCurrentMode(), split: function() { that._doSplit = true; that._doCollapse = false; }, collapse: function() { that._doSplit = false; that._doCollapse = true; }, width: window.innerWidth, orientation: this._getOrientation() }); }, _activateCollapseMode: function() { if (this._mode !== COLLAPSE_MODE) { this._fireEvent('precollapse'); this._secondaryPage.attr('style', ''); this._mainPage.attr('style', ''); this._mode = COLLAPSE_MODE; this._animator.setup( this._element, this._mainPage, this._secondaryPage, {isRight: false, width: '90%'} ); this._fireEvent('postcollapse'); } }, _activateSplitMode: function() { if (this._mode !== SPLIT_MODE) { this._fireEvent('presplit'); this._animator.destroy(); this._secondaryPage.attr('style', ''); this._mainPage.attr('style', ''); this._mode = SPLIT_MODE; this._setSize(); this._fireEvent('postsplit'); } }, _destroy: function() { this.emit('destroy'); this._element = null; this._scope = null; } }); function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } MicroEvent.mixin(SplitView); return SplitView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){ 'use strict'; var module = angular.module('onsen'); module.factory('SwitchView', ['$onsen', function($onsen) { var SwitchView = Class.extend({ /** * @param {jqLite} element * @param {Object} scope * @param {Object} attrs */ init: function(element, scope, attrs) { this._element = element; this._checkbox = angular.element(element[0].querySelector('input[type=checkbox]')); this._scope = scope; attrs.$observe('disabled', function(disabled) { if (!!element.attr('disabled')) { this._checkbox.attr('disabled', 'disabled'); } else { this._checkbox.removeAttr('disabled'); } }.bind(this)); this._checkbox.on('change', function(event) { this.emit('change', {'switch': this, value: this._checkbox[0].checked, isInteractive: true}); }.bind(this)); }, /** * @return {Boolean} */ isChecked: function() { return this._checkbox[0].checked; }, /** * @param {Boolean} */ setChecked: function(isChecked) { isChecked = !!isChecked; if (this._checkbox[0].checked != isChecked) { this._scope.model = isChecked; this._checkbox[0].checked = isChecked; this._scope.$evalAsync(); this.emit('change', {'switch': this, value: isChecked, isInteractive: false}); } }, /** * @return {HTMLElement} */ getCheckboxElement: function() { return this._checkbox[0]; } }); MicroEvent.mixin(SwitchView); return SwitchView; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function() { 'use strict;'; var module = angular.module('onsen'); module.factory('TabbarAnimator', function() { var TabbarAnimator = Class.extend({ /** * @param {jqLite} enterPage * @param {jqLite} leavePage */ apply: function(enterPage, leavePage, done) { throw new Error('This method must be implemented.'); } }); return TabbarAnimator; }); module.factory('TabbarNoneAnimator', ['TabbarAnimator', function(TabbarAnimator) { var TabbarNoneAnimator = TabbarAnimator.extend({ /** * @param {jqLite} enterPage * @param {jqLite} leavePage */ apply: function(enterPage, leavePage, done) { done(); } }); return TabbarNoneAnimator; }]); module.factory('TabbarFadeAnimator', ['TabbarAnimator', function(TabbarAnimator) { var TabbarFadeAnimator = TabbarAnimator.extend({ /** * @param {jqLite} enterPage * @param {jqLite} leavePage */ apply: function(enterPage, leavePage, done) { animit.runAll( animit(enterPage[0]) .queue({ transform: 'translate3D(0, 0, 0)', opacity: 0 }) .queue({ transform: 'translate3D(0, 0, 0)', opacity: 1 }, { duration: 0.4, timing: 'linear' }) .resetStyle() .queue(function(callback) { done(); callback(); }), animit(leavePage[0]) .queue({ transform: 'translate3D(0, 0, 0)', opacity: 1 }) .queue({ transform: 'translate3D(0, 0, 0)', opacity: 0 }, { duration: 0.4, timing: 'linear' }) ); } }); return TabbarFadeAnimator; }]); module.factory('TabbarView', ['$onsen', '$compile', 'TabbarAnimator', 'TabbarNoneAnimator', 'TabbarFadeAnimator', function($onsen, $compile, TabbarAnimator, TabbarNoneAnimator, TabbarFadeAnimator) { var TabbarView = Class.extend({ _tabbarId: undefined, _tabItems: undefined, init: function(scope, element, attrs) { this._scope = scope; this._element = element; this._attrs = attrs; this._tabbarId = Date.now(); this._tabItems = []; this._contentElement = angular.element(element[0].querySelector('.ons-tab-bar__content')); this._tabbarElement = angular.element(element[0].querySelector('.ons-tab-bar__footer')); this._scope.$on('$destroy', this._destroy.bind(this)); if (this._hasTopTabbar()) { this._prepareForTopTabbar(); } }, _prepareForTopTabbar: function() { this._contentElement.attr('no-status-bar-fill', ''); setImmediate(function() { this._contentElement.addClass('tab-bar--top__content'); this._tabbarElement.addClass('tab-bar--top'); }.bind(this)); var page = ons.findParentComponentUntil('ons-page', this._element[0]); if (page) { this._element.css('top', window.getComputedStyle(page.getContentElement(), null).getPropertyValue('padding-top')); } if ($onsen.shouldFillStatusBar(this._element[0])) { // Adjustments for IOS7 var fill = angular.element(document.createElement('div')); fill.addClass('tab-bar__status-bar-fill'); fill.css({width: '0px', height: '0px'}); this._element.prepend(fill); } }, _hasTopTabbar: function() { return this._attrs.position === 'top'; }, /** * @param {Number} index * @param {Object} [options] * @param {Boolean} [options.keepPage] * @param {String} [options.animation] * @return {Boolean} success or not */ setActiveTab: function(index, options) { options = options || {}; var previousTabItem = this._tabItems[this.getActiveTabIndex()]; var selectedTabItem = this._tabItems[index]; if ((typeof selectedTabItem.noReload !== 'undefined' || selectedTabItem.isPersistent()) && index === this.getActiveTabIndex()) { this.emit('reactive', { index: index, tabItem: selectedTabItem, }); return false; } var needLoad = selectedTabItem.page && !options.keepPage; if (!selectedTabItem) { return false; } var canceled = false; this.emit('prechange', { index: index, tabItem: selectedTabItem, cancel: function() { canceled = true; } }); if (canceled) { selectedTabItem.setInactive(); if (previousTabItem) { previousTabItem.setActive(); } return false; } selectedTabItem.setActive(); if (needLoad) { var removeElement = true; if (previousTabItem && previousTabItem.isPersistent()) { removeElement = false; previousTabItem._pageElement = this._currentPageElement; } var params = { callback: function() { this.emit('postchange', {index: index, tabItem: selectedTabItem}); }.bind(this), _removeElement: removeElement }; if (options.animation) { params.animation = options.animation; } if (selectedTabItem.isPersistent() && selectedTabItem._pageElement) { this._loadPersistentPageDOM(selectedTabItem._pageElement, params); } else { this._loadPage(selectedTabItem.page, params); } } for (var i = 0; i < this._tabItems.length; i++) { if (this._tabItems[i] != selectedTabItem) { this._tabItems[i].setInactive(); } else { if (!needLoad) { this.emit('postchange', {index: index, tabItem: selectedTabItem}); } } } return true; }, /** * @param {Boolean} visible */ setTabbarVisibility: function(visible) { this._scope.hideTabs = !visible; this._onTabbarVisibilityChanged(); }, _onTabbarVisibilityChanged: function() { if (this._hasTopTabbar()) { if (this._scope.hideTabs) { this._contentElement.css('top', '0px'); } else { this._contentElement.css('top', ''); } } else { if (this._scope.hideTabs) { this._contentElement.css('bottom', '0px'); } else { this._contentElement.css('bottom', ''); } } }, /** * @param {Object} tabItem */ addTabItem: function(tabItem) { this._tabItems.push(tabItem); }, /** * @return {Number} When active tab is not found, returns -1. */ getActiveTabIndex: function() { var tabItem; for (var i = 0; i < this._tabItems.length; i++) { tabItem = this._tabItems[i]; if (tabItem.isActive()) { return i; } } return -1; }, /** * @param {String} page * @param {Object} [options] * @param {Object} [options.animation] * @param {Object} [options.callback] */ loadPage: function(page, options) { return this._loadPage(page, options); }, /** * @param {String} page * @param {Object} [options] * @param {Object} [options.animation] */ _loadPage: function(page, options) { $onsen.getPageHTMLAsync(page).then(function(html) { var pageElement = angular.element(html.trim()); this._loadPageDOM(pageElement, options); }.bind(this), function() { throw new Error('Page is not found: ' + page); }); }, /** * @param {jqLite} element * @param {Object} scope * @param {Object} options * @param {Object} options.animation */ _switchPage: function(element, options) { if (this._currentPageElement) { var oldPageElement = this._currentPageElement; var oldPageScope = this._currentPageScope; this._currentPageElement = element; this._currentPageScope = element.data('_scope'); this._getAnimatorOption(options).apply(element, oldPageElement, function() { if (options._removeElement) { oldPageElement.remove(); oldPageScope.$destroy(); } else { oldPageElement.css('display', 'none'); } if (options.callback instanceof Function) { options.callback(); } }); } else { this._currentPageElement = element; this._currentPageScope = element.data('_scope'); if (options.callback instanceof Function) { options.callback(); } } }, /** * @param {jqLite} element * @param {Object} options * @param {Object} options.animation */ _loadPageDOM: function(element, options) { options = options || {}; var pageScope = this._scope.$new(); var link = $compile(element); this._contentElement.append(element); var pageContent = link(pageScope); pageScope.$evalAsync(); this._switchPage(pageContent, options); }, /** * @param {jqLite} element * @param {Object} options * @param {Object} options.animation */ _loadPersistentPageDOM: function(element, options) { options = options || {}; element.css('display', 'block'); this._switchPage(element, options); }, /** * @param {Object} options * @param {String} [options.animation] * @return {TabbarAnimator} */ _getAnimatorOption: function(options) { var animationAttr = this._element.attr('animation') || 'default'; return TabbarView._animatorDict[options.animation || animationAttr] || TabbarView._animatorDict['default']; }, _destroy: function() { this.emit('destroy'); this._element = this._scope = this._attrs = null; } }); MicroEvent.mixin(TabbarView); // Preset transition animators. TabbarView._animatorDict = { 'default': new TabbarNoneAnimator(), 'none': new TabbarNoneAnimator(), 'fade': new TabbarFadeAnimator() }; /** * @param {String} name * @param {NavigatorTransitionAnimator} animator */ TabbarView.registerAnimator = function(name, animator) { if (!(animator instanceof TabbarAnimator)) { throw new Error('"animator" param must be an instance of TabbarAnimator'); } this._animatorDict[name] = animator; }; return TabbarView; }]); })(); /** * @ngdoc directive * @id alert-dialog * @name ons-alert-dialog * @category dialog * @modifier android * [en]Display an Android style alert dialog.[/en] * [ja]Androidライクなスタイルを表示します。[/ja] * @description * [en]Alert dialog that is displayed on top of the current screen.[/en] * [ja]現在のスクリーンにアラートダイアログを表示します。[/ja] * @codepen Qwwxyp * @guide UsingAlert * [en]Learn how to use the alert dialog.[/en] * [ja]アラートダイアログの使い方の解説。[/ja] * @seealso ons-dialog * [en]ons-dialog component[/en] * [ja]ons-dialogコンポーネント[/ja] * @seealso ons-popover * [en]ons-popover component[/en] * [ja]ons-dialogコンポーネント[/ja] * @seealso ons.notification * [en]Using ons.notification utility functions.[/en] * [ja]アラートダイアログを表示するには、ons.notificationオブジェクトのメソッドを使うこともできます。[/ja] * @example * <script> * ons.ready(function() { * ons.createAlertDialog('alert.html').then(function(alertDialog) { * alertDialog.show(); * }); * }); * </script> * * <script type="text/ons-template" id="alert.html"> * <ons-alert-dialog animation="default" cancelable> * <div class="alert-dialog-title">Warning!</div> * <div class="alert-dialog-content"> * An error has occurred! * </div> * <div class="alert-dialog-footer"> * <button class="alert-dialog-button">OK</button> * </div> * </ons-alert-dialog> * </script> */ /** * @ngdoc event * @name preshow * @description * [en]Fired just before the alert dialog is displayed.[/en] * [ja]アラートダイアログが表示される直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.alertDialog * [en]Alert dialog object.[/en] * [ja]アラートダイアログのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Execute to stop the dialog from showing.[/en] * [ja]この関数を実行すると、アラートダイアログの表示を止めます。[/ja] */ /** * @ngdoc event * @name postshow * @description * [en]Fired just after the alert dialog is displayed.[/en] * [ja]アラートダイアログが表示された直後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.alertDialog * [en]Alert dialog object.[/en] * [ja]アラートダイアログのオブジェクト。[/ja] */ /** * @ngdoc event * @name prehide * @description * [en]Fired just before the alert dialog is hidden.[/en] * [ja]アラートダイアログが隠れる直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.alertDialog * [en]Alert dialog object.[/en] * [ja]アラートダイアログのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Execute to stop the dialog from hiding.[/en] * [ja]この関数を実行すると、アラートダイアログが閉じようとするのを止めます。[/ja] */ /** * @ngdoc event * @name posthide * @description * [en]Fired just after the alert dialog is hidden.[/en] * [ja]アラートダイアログが隠れた後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.alertDialog * [en]Alert dialog object.[/en] * [ja]アラートダイアログのオブジェクト。[/ja] */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this alert dialog.[/en] * [ja]このアラートダイアログを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the dialog.[/en] * [ja]ダイアログの見た目を指定します。[/ja] */ /** * @ngdoc attribute * @name cancelable * @description * [en]If this attribute is set the dialog can be closed by tapping the background or by pressing the back button.[/en] * [ja]この属性があると、ダイアログが表示された時に、背景やバックボタンをタップした時にダイアログを閉じます。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set the dialog is disabled.[/en] * [ja]この属性がある時、アラートダイアログはdisabled状態になります。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @default default * @description * [en]The animation used when showing and hiding the dialog. Can be either "none" or "default".[/en] * [ja]ダイアログを表示する際のアニメーション名を指定します。デフォルトでは"none"か"default"が指定できます。[/ja] */ /** * @ngdoc attribute * @name mask-color * @type {String} * @default rgba(0, 0, 0, 0.2) * @description * [en]Color of the background mask. Default is "rgba(0, 0, 0, 0.2)".[/en] * [ja]背景のマスクの色を指定します。"rgba(0, 0, 0, 0.2)"がデフォルト値です。[/ja] */ /** * @ngdoc attribute * @name ons-preshow * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en] * [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-prehide * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en] * [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postshow * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en] * [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-posthide * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en] * [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature show([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクトです。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "fade", "slide" and "none".[/en] * [ja]アニメーション名を指定します。指定できるのは、"fade", "slide", "none"のいずれかです。[/ja] * @param {Function} [options.callback] * [en]Function to execute after the dialog has been revealed.[/en] * [ja]ダイアログが表示され終わった時に呼び出されるコールバックを指定します。[/ja] * @description * [en]Show the alert dialog.[/en] * [ja]ダイアログを表示します。[/ja] */ /** * @ngdoc method * @signature hide([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "fade", "slide" and "none".[/en] * [ja]アニメーション名を指定します。"fade", "slide", "none"のいずれかを指定します。[/ja] * @param {Function} [options.callback] * [en]Function to execute after the dialog has been hidden.[/en] * [ja]このダイアログが閉じた時に呼び出されるコールバックを指定します。[/ja] * @description * [en]Hide the alert dialog.[/en] * [ja]ダイアログを閉じます。[/ja] */ /** * @ngdoc method * @signature isShown() * @description * [en]Returns whether the dialog is visible or not.[/en] * [ja]ダイアログが表示されているかどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is currently visible.[/en] * [ja]ダイアログが表示されていればtrueを返します。[/ja] */ /** * @ngdoc method * @signature destroy() * @description * [en]Destroy the alert dialog and remove it from the DOM tree.[/en] * [ja]ダイアログを破棄して、DOMツリーから取り除きます。[/ja] */ /** * @ngdoc method * @signature setCancelable(cancelable) * @description * [en]Define whether the dialog can be canceled by the user or not.[/en] * [ja]アラートダイアログを表示した際に、ユーザがそのダイアログをキャンセルできるかどうかを指定します。[/ja] * @param {Boolean} cancelable * [en]If true the dialog will be cancelable.[/en] * [ja]キャンセルできるかどうかを真偽値で指定します。[/ja] */ /** * @ngdoc method * @signature isCancelable() * @description * [en]Returns whether the dialog is cancelable or not.[/en] * [ja]このアラートダイアログがキャンセル可能かどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is cancelable.[/en] * [ja]キャンセル可能であればtrueを返します。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @description * [en]Disable or enable the alert dialog.[/en] * [ja]このアラートダイアログをdisabled状態にするかどうかを設定します。[/ja] * @param {Boolean} disabled * [en]If true the dialog will be disabled.[/en] * [ja]disabled状態にするかどうかを真偽値で指定します。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @description * [en]Returns whether the dialog is disabled or enabled.[/en] * [ja]このアラートダイアログがdisabled状態かどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is disabled.[/en] * [ja]disabled状態であればtrueを返します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火された際に呼び出されるコールバックを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出されるコールバックを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしlistenerパラメータが指定されなかった場合、そのイベントのリスナーが全て削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーの関数オブジェクトを渡します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); /** * Alert dialog directive. */ module.directive('onsAlertDialog', ['$onsen', 'AlertDialogView', function($onsen, AlertDialogView) { return { restrict: 'E', replace: false, scope: true, transclude: false, compile: function(element, attrs) { var modifierTemplater = $onsen.generateModifierTemplater(attrs); element.addClass('alert-dialog ' + modifierTemplater('alert-dialog--*')); var titleElement = angular.element(element[0].querySelector('.alert-dialog-title')), contentElement = angular.element(element[0].querySelector('.alert-dialog-content')); if (titleElement.length) { titleElement.addClass(modifierTemplater('alert-dialog-title--*')); } if (contentElement.length) { contentElement.addClass(modifierTemplater('alert-dialog-content--*')); } return { pre: function(scope, element, attrs) { var alertDialog = new AlertDialogView(scope, element, attrs); $onsen.declareVarAttribute(attrs, alertDialog); $onsen.registerEventHandlers(alertDialog, 'preshow prehide postshow posthide destroy'); $onsen.addModifierMethods(alertDialog, 'alert-dialog--*', element); if (titleElement.length) { $onsen.addModifierMethods(alertDialog, 'alert-dialog-title--*', titleElement); } if (contentElement.length) { $onsen.addModifierMethods(alertDialog, 'alert-dialog-content--*', contentElement); } if ($onsen.isAndroid()) { alertDialog.addModifier('android'); } element.data('ons-alert-dialog', alertDialog); scope.$on('$destroy', function() { alertDialog._events = undefined; $onsen.removeModifierMethods(alertDialog); element.data('ons-alert-dialog', undefined); element = null; }); }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id back_button * @name ons-back-button * @category toolbar * @description * [en]Back button component for ons-toolbar. Can be used with ons-navigator to provide back button support.[/en] * [ja]ons-toolbarに配置できる「戻るボタン」用コンポーネントです。ons-navigatorと共に使用し、ページを1つ前に戻る動作を行います。[/ja] * @codepen aHmGL * @seealso ons-toolbar * [en]ons-toolbar component[/en] * [ja]ons-toolbarコンポーネント[/ja] * @seealso ons-navigator * [en]ons-navigator component[/en] * [ja]ons-navigatorコンポーネント[/en] * @guide Addingatoolbar * [en]Adding a toolbar[/en] * [ja]ツールバーの追加[/ja] * @guide Returningfromapage * [en]Returning from a page[/en] * [ja]一つ前のページに戻る[/ja] * @example * <ons-back-button> * Back * </ons-back-button> */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsBackButton', ['$onsen', '$compile', 'GenericView', 'ComponentCleaner', function($onsen, $compile, GenericView, ComponentCleaner) { return { restrict: 'E', replace: false, templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/back_button.tpl', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: true, scope: true, link: { pre: function(scope, element, attrs, controller, transclude) { var backButton = new GenericView(scope, element, attrs); $onsen.declareVarAttribute(attrs, backButton); element.data('ons-back-button', backButton); scope.$on('$destroy', function() { backButton._events = undefined; $onsen.removeModifierMethods(backButton); element.data('ons-back-button', undefined); element = null; }); scope.modifierTemplater = $onsen.generateModifierTemplater(attrs); var navigator = ons.findParentComponentUntil('ons-navigator', element); scope.$watch(function() { return navigator.pages.length; }, function(nbrOfPages) { scope.showBackButton = nbrOfPages > 1; }); $onsen.addModifierMethods(backButton, 'toolbar-button--*', element.children()); transclude(scope, function(clonedElement) { if (clonedElement[0]) { element[0].querySelector('.back-button__label').appendChild(clonedElement[0]); } }); ComponentCleaner.onDestroy(scope, function() { ComponentCleaner.destroyScope(scope); ComponentCleaner.destroyAttributes(attrs); element = null; scope = null; attrs = null; }); }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } } }; }]); })(); /** * @ngdoc directive * @id bottom_toolbar * @name ons-bottom-toolbar * @category toolbar * @description * [en]Toolbar component that is positioned at the bottom of the page.[/en] * [ja]ページ下部に配置されるツールバー用コンポーネントです。[/ja] * @modifier transparent * [en]Make the toolbar transparent.[/en] * [ja]ツールバーの背景を透明にして表示します。[/ja] * @seealso ons-toolbar [en]ons-toolbar component[/en][ja]ons-toolbarコンポーネント[/ja] * @guide Addingatoolbar * [en]Adding a toolbar[/en] * [ja]ツールバーの追加[/ja] * @example * <ons-bottom-toolbar> * <div style="text-align: center; line-height: 44px">Text</div> * </ons-bottom-toolbar> */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the toolbar.[/en] * [ja]ツールバーの見た目の表現を指定します。[/ja] */ /** * @ngdoc attribute * @name inline * @description * [en]Display the toolbar as an inline element.[/en] * [ja]この属性があると、ツールバーを画面下部ではなくスクロール領域内にそのまま表示します。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsBottomToolbar', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclde. transclude: false, scope: false, compile: function(element, attrs) { var modifierTemplater = $onsen.generateModifierTemplater(attrs), inline = typeof attrs.inline !== 'undefined'; element.addClass('bottom-bar'); element.addClass(modifierTemplater('bottom-bar--*')); element.css({'z-index': 0}); if (inline) { element.css('position', 'static'); } return { pre: function(scope, element, attrs) { var bottomToolbar = new GenericView(scope, element, attrs); $onsen.declareVarAttribute(attrs, bottomToolbar); element.data('ons-bottomToolbar', bottomToolbar); scope.$on('$destroy', function() { bottomToolbar._events = undefined; $onsen.removeModifierMethods(bottomToolbar); element.data('ons-bottomToolbar', undefined); element = null; }); $onsen.addModifierMethods(bottomToolbar, 'bottom-bar--*', element); var pageView = element.inheritedData('ons-page'); if (pageView && !inline) { pageView.registerBottomToolbar(element); } }, post: function(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id button * @name ons-button * @category form * @modifier outline * [en]Button with outline and transparent background[/en] * [ja]アウトラインを持ったボタンを表示します。[/ja] * @modifier light * [en]Button that doesn't stand out.[/en] * [ja]目立たないボタンを表示します。[/ja] * @modifier quiet * [en]Button with no outline and or background..[/en] * [ja]枠線や背景が無い文字だけのボタンを表示します。[/ja] * @modifier cta * [en]Button that really stands out.[/en] * [ja]目立つボタンを表示します。[/ja] * @modifier large * [en]Large button that covers the width of the screen.[/en] * [ja]横いっぱいに広がる大きなボタンを表示します。[/ja] * @modifier large--quiet * [en]Large quiet button.[/en] * [ja]横いっぱいに広がるquietボタンを表示します。[/ja] * @modifier large--cta * [en]Large call to action button.[/en] * [ja]横いっぱいに広がるctaボタンを表示します。[/ja] * @description * [en]Button component. If you want to place a button in a toolbar, use ons-toolbar-button or ons-back-button instead.[/en] * [ja]ボタン用コンポーネント。ツールバーにボタンを設置する場合は、ons-toolbar-buttonもしくはons-back-buttonコンポーネントを使用します。[/ja] * @codepen hLayx * @guide Button [en]Guide for ons-button[/en][ja]ons-buttonの使い方[/ja] * @guide OverridingCSSstyles [en]More details about modifier attribute[/en][ja]modifier属性の使い方[/ja] * @example * <ons-button modifier="large--cta"> * Tap Me * </ons-button> */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the button.[/en] * [ja]ボタンの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name should-spin * @type {Boolean} * @description * [en]Specify if the button should have a spinner. [/en] * [ja]ボタンにスピナーを表示する場合に指定します。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @description * [en]The animation when the button transitions to and from the spinner. Possible values are "slide-left" (default), "slide-right", "slide-up", "slide-down", "expand-left", "expand-right", "expand-up", "expand-down", "zoom-out", "zoom-in".[/en] * [ja]スピナーを表示する場合のアニメーションを指定します。"slide-left" (デフォルト), "slide-right", "slide-up", "slide-down", "expand-left", "expand-right", "expand-up", "expand-down", "zoom-out", "zoom-in"のいずれかを指定します。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]Specify if button should be disabled.[/en] * [ja]ボタンを無効化する場合は指定します。[/ja] */ /** * @ngdoc method * @signature startSpin() * @description * [en]Show spinner on the button.[/en] * [ja]ボタンにスピナーを表示します。[/ja] */ /** * @ngdoc method * @signature stopSpin() * @description * [en]Remove spinner from button.[/en] * [ja]ボタンのスピナーを隠します。[/ja] */ /** * @ngdoc method * @signature isSpinning() * @return {Boolean} * [en]true if the button is spinning.[/en] * [ja]spinしているかどうかを返します。[/ja] * @description * [en]Return whether the spinner is visible or not.[/en] * [ja]ボタン内にスピナーが表示されているかどうかを返します。[/ja] */ /** * @ngdoc method * @signature setSpinAnimation(animation) * @description * [en]Set spin animation. Possible values are "slide-left" (default), "slide-right", "slide-up", "slide-down", "expand-left", "expand-right", "expand-up", "expand-down", "zoom-out", "zoom-in".[/en] * [ja]スピナーを表示する場合のアニメーションを指定します。"slide-left" (デフォルト), "slide-right", "slide-up", "slide-down", "expand-left", "expand-right", "expand-up", "expand-down", "zoom-out", "zoom-in"のいずれかを指定します。[/ja] * @param {String} animation * [en]Animation name.[/en] * [ja]アニメーション名を指定します。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @description * [en]Disable or enable the button.[/en] * [ja]このボタンをdisabled状態にするかどうかを設定します。[/ja] * @param {String} disabled * [en]If true the button will be disabled.[/en] * [ja]disabled状態にするかどうかを真偽値で指定します。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @return {Boolean} * [en]true if the button is disabled.[/en] * [ja]ボタンがdisabled状態になっているかどうかを返します。[/ja] * @description * [en]Returns whether the button is disabled or enabled.[/en] * [ja]このボタンがdisabled状態かどうかを返します。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsButton', ['$onsen', 'ButtonView', function($onsen, ButtonView) { return { restrict: 'E', replace: false, transclude: true, scope: { animation: '@', }, templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/button.tpl', link: function(scope, element, attrs, _, transclude) { var button = new ButtonView(scope, element, attrs); $onsen.declareVarAttribute(attrs, button); element.data('ons-button', button); scope.$on('$destroy', function() { button._events = undefined; $onsen.removeModifierMethods(button); element.data('ons-button', undefined); element = null; }); var initialAnimation = 'slide-left'; scope.modifierTemplater = $onsen.generateModifierTemplater(attrs); element.addClass('button effeckt-button'); element.addClass(scope.modifierTemplater('button--*')); element.addClass(initialAnimation); $onsen.addModifierMethods(button, 'button--*', element); transclude(scope.$parent, function(cloned) { angular.element(element[0].querySelector('.ons-button-inner')).append(cloned); }); if (attrs.ngController) { throw new Error('This element can\'t accept ng-controller directive.'); } scope.item = {}; // if animation is not specified -> default is slide-left scope.item.animation = initialAnimation; scope.$watch('animation', function(newAnimation) { if (newAnimation) { if (scope.item.animation) { element.removeClass(scope.item.animation); } scope.item.animation = newAnimation; element.addClass(scope.item.animation); } }); attrs.$observe('shouldSpin', function(shouldSpin) { if (shouldSpin === 'true') { element.attr('data-loading', true); } else { element.removeAttr('data-loading'); } }); $onsen.cleaner.onDestroy(scope, function() { $onsen.clearComponent({ scope: scope, attrs: attrs, element: element }); scope = element = attrs = null; }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id carousel * @name ons-carousel * @category carousel * @description * [en]Carousel component.[/en] * [ja]カルーセルを表示できるコンポーネント。[/ja] * @codepen xbbzOQ * @guide UsingCarousel * [en]Learn how to use the carousel component.[/en] * [ja]carouselコンポーネントの使い方[/ja] * @example * <ons-carousel style="width: 100%; height: 200px"> * <ons-carousel-item> * ... * </ons-carousel-item> * <ons-carousel-item> * ... * </ons-carousel-item> * </ons-carousel> */ /** * @ngdoc event * @name postchange * @description * [en]Fired just after the current carousel item has changed.[/en] * [ja]現在表示しているカルーセルの要素が変わった時に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.carousel * [en]Carousel object.[/en] * [ja]イベントが発火したCarouselオブジェクトです。[/ja] * @param {Number} event.activeIndex * [en]Current active index.[/en] * [ja]現在アクティブになっている要素のインデックス。[/ja] * @param {Number} event.lastActiveIndex * [en]Previous active index.[/en] * [ja]以前アクティブだった要素のインデックス。[/ja] */ /** * @ngdoc event * @name refresh * @description * [en]Fired when the carousel has been refreshed.[/en] * [ja]カルーセルが更新された時に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.carousel * [en]Carousel object.[/en] * [ja]イベントが発火したCarouselオブジェクトです。[/ja] */ /** * @ngdoc event * @name overscroll * @description * [en]Fired when the carousel has been overscrolled.[/en] * [ja]カルーセルがオーバースクロールした時に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.carousel * [en]Fired when the carousel has been refreshed.[/en] * [ja]カルーセルが更新された時に発火します。[/ja] * @param {Number} event.activeIndex * [en]Current active index.[/en] * [ja]現在アクティブになっている要素のインデックス。[/ja] * @param {String} event.direction * [en]Can be one of either "up", "down", "left" or "right".[/en] * [ja]オーバースクロールされた方向が得られます。"up", "down", "left", "right"のいずれかの方向が渡されます。[/ja] * @param {Function} event.waitToReturn * [en]Takes a <code>Promise</code> object as an argument. The carousel will not scroll back until the promise has been resolved or rejected.[/en] * [ja]この関数はPromiseオブジェクトを引数として受け取ります。渡したPromiseオブジェクトがresolveされるかrejectされるまで、カルーセルはスクロールバックしません。[/ja] */ /** * @ngdoc attribute * @name direction * @type {String} * @description * [en]The direction of the carousel. Can be either "horizontal" or "vertical". Default is "horizontal".[/en] * [ja]カルーセルの方向を指定します。"horizontal"か"vertical"を指定できます。"horizontal"がデフォルト値です。[/ja] */ /** * @ngdoc attribute * @name fullscreen * @description * [en]If this attribute is set the carousel will cover the whole screen.[/en] * [ja]この属性があると、absoluteポジションを使ってカルーセルが自動的に画面いっぱいに広がります。[/ja] */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this carousel.[/en] * [ja]このカルーセルを参照するための変数名を指定します。[/ja] */ /** * @ngdoc attribute * @name overscrollable * @description * [en]If this attribute is set the carousel will be scrollable over the edge. It will bounce back when released.[/en] * [ja]この属性がある時、タッチやドラッグで端までスクロールした時に、バウンドするような効果が当たります。[/ja] */ /** * @ngdoc attribute * @name item-width * @type {String} * @description * [en]ons-carousel-item's width. Only works when the direction is set to "horizontal".[/en] * [ja]ons-carousel-itemの幅を指定します。この属性は、direction属性に"horizontal"を指定した時のみ有効になります。[/ja] */ /** * @ngdoc attribute * @name item-height * @type {String} * @description * [en]ons-carousel-item's height. Only works when the direction is set to "vertical".[/en] * [ja]ons-carousel-itemの高さを指定します。この属性は、direction属性に"vertical"を指定した時のみ有効になります。[/ja] */ /** * @ngdoc attribute * @name auto-scroll * @description * [en]If this attribute is set the carousel will be automatically scrolled to the closest item border when released.[/en] * [ja]この属性がある時、一番近いcarosel-itemの境界まで自動的にスクロールするようになります。[/ja] */ /** * @ngdoc attribute * @name auto-scroll-ratio * @type {Number} * @description * [en]A number between 0.0 and 1.0 that specifies how much the user must drag the carousel in order for it to auto scroll to the next item.[/en] * [ja]0.0から1.0までの値を指定します。カルーセルの要素をどれぐらいの割合までドラッグすると次の要素に自動的にスクロールするかを指定します。[/ja] */ /** * @ngdoc attribute * @name swipeable * @description * [en]If this attribute is set the carousel can be scrolled by drag or swipe.[/en] * [ja]この属性がある時、カルーセルをスワイプやドラッグで移動できるようになります。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set the carousel is disabled.[/en] * [ja]この属性がある時、dragやtouchやswipeを受け付けなくなります。[/ja] */ /** * @ngdoc attribute * @name intial-index * @type {Number} * @description * [en]Specify the index of the ons-carousel-item to show initially. Default is 0.[/en] * [ja]最初に表示するons-carousel-itemを0始まりのインデックスで指定します。デフォルト値は 0 です。[/ja] */ /** * @ngdoc attribute * @name auto-refresh * @description * [en]When this attribute is set the carousel will automatically refresh when the number of child nodes change.[/en] * [ja]この属性がある時、子要素の数が変わるとカルーセルは自動的に更新されるようになります。[/ja] */ /** * @ngdoc attribute * @name ons-postchange * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postchange" event is fired.[/en] * [ja]"postchange"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-refresh * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "refresh" event is fired.[/en] * [ja]"refresh"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-overscroll * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "overscroll" event is fired.[/en] * [ja]"overscroll"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature next() * @description * [en]Show next ons-carousel item.[/en] * [ja]次のons-carousel-itemを表示します。[/ja] */ /** * @ngdoc method * @signature prev() * @description * [en]Show previous ons-carousel item.[/en] * [ja]前のons-carousel-itemを表示します。[/ja] */ /** * @ngdoc method * @signature first() * @description * [en]Show first ons-carousel item.[/en] * [ja]最初のons-carousel-itemを表示します。[/ja] */ /** * @ngdoc method * @signature last() * @description * [en]Show last ons-carousel item.[/en] * [ja]最後のons-carousel-itemを表示します。[/ja] */ /** * @ngdoc method * @signature setSwipeable(swipeable) * @param {Booelan} swipeable * [en]If value is true the carousel will be swipeable.[/en] * [ja]swipeableにする場合にはtrueを指定します。[/ja] * @description * [en]Set whether the carousel is swipeable or not.[/en] * [ja]swipeできるかどうかを指定します。[/ja] */ /** * @ngdoc method * @signature isSwipeable() * @return {Boolean} * [en]true if the carousel is swipeable.[/en] * [ja]swipeableであればtrueを返します。[/ja] * @description * [en]Returns whether the carousel is swipeable or not.[/en] * [ja]swiapble属性があるかどうかを返します。[/ja] */ /** * @ngdoc method * @signature setActiveCarouselItemIndex(index) * @param {Number} index * [en]The index that the carousel should be set to.[/en] * [ja]carousel要素のインデックスを指定します。[/ja] * @description * [en]Specify the index of the ons-carousel-item to show.[/en] * [ja]表示するons-carousel-itemをindexで指定します。[/ja] */ /** * @ngdoc method * @signature getActiveCarouselItemIndex() * @return {Number} * [en]The current carousel item index.[/en] * [ja]現在表示しているカルーセル要素のインデックスが返されます。[/ja] * @description * [en]Returns the index of the currently visible ons-carousel-item.[/en] * [ja]現在表示されているons-carousel-item要素のインデックスを返します。[/ja] */ /** * @ngdoc method * @signature setAutoScrollEnabled(enabled) * @param {Boolean} enabled * [en]If true auto scroll will be enabled.[/en] * [ja]オートスクロールを有効にする場合にはtrueを渡します。[/ja] * @description * [en]Enable or disable "auto-scroll" attribute.[/en] * [ja]auto-scroll属性があるかどうかを設定します。[/ja] */ /** * @ngdoc method * @signature isAutoScrollEnabled() * @return {Boolean} * [en]true if auto scroll is enabled.[/en] * [ja]オートスクロールが有効であればtrueを返します。[/ja] * @description * [en]Returns whether the "auto-scroll" attribute is set or not.[/en] * [ja]auto-scroll属性があるかどうかを返します。[/ja] */ /** * @ngdoc method * @signature setAutoScrollRatio(ratio) * @param {Number} ratio * [en]The desired ratio.[/en] * [ja]オートスクロールするのに必要な0.0から1.0までのratio値を指定します。[/ja] * @description * [en]Set the auto scroll ratio. Must be a value between 0.0 and 1.0.[/en] * [ja]オートスクロールするのに必要なratio値を指定します。0.0から1.0を必ず指定しなければならない。[/ja] */ /** * @ngdoc method * @signature getAutoScrollRatio() * @return {Number} * [en]The current auto scroll ratio.[/en] * [ja]現在のオートスクロールのratio値。[/ja] * @description * [en]Returns the current auto scroll ratio.[/en] * [ja]現在のオートスクロールのratio値を返します。[/ja] */ /** * @ngdoc method * @signature setOverscrollable(overscrollable) * @param {Boolean} overscrollable * [en]If true the carousel will be overscrollable.[/en] * [ja]overscrollできるかどうかを指定します。[/ja] * @description * [en]Set whether the carousel is overscrollable or not.[/en] * [ja]overscroll属性があるかどうかを設定します。[/ja] */ /** * @ngdoc method * @signature isOverscrollable() * @return {Boolean} * [en]Whether the carousel is overscrollable or not.[/en] * [ja]overscrollできればtrueを返します。[/ja] * @description * [en]Returns whether the carousel is overscrollable or not.[/en] * [ja]overscroll属性があるかどうかを返します。[/ja] */ /** * @ngdoc method * @signature refresh() * @description * [en]Update the layout of the carousel. Used when adding ons-carousel-items dynamically or to automatically adjust the size.[/en] * [ja]レイアウトや内部の状態を最新のものに更新します。ons-carousel-itemを動的に増やしたり、ons-carouselの大きさを動的に変える際に利用します。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @return {Boolean} * [en]Whether the carousel is disabled or not.[/en] * [ja]disabled状態になっていればtrueを返します。[/ja] * @description * [en]Returns whether the dialog is disabled or enabled.[/en] * [ja]disabled属性があるかどうかを返します。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @param {Boolean} disabled * [en]If true the carousel will be disabled.[/en] * [ja]disabled状態にする場合にはtrueを指定します。[/ja] * @description * [en]Disable or enable the dialog.[/en] * [ja]disabled属性があるかどうかを設定します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーが指定されなかった場合には、そのイベントに紐付いているイベントリスナーが全て削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsCarousel', ['$onsen', 'CarouselView', function($onsen, CarouselView) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. scope: false, transclude: false, compile: function(element, attrs) { var templater = $onsen.generateModifierTemplater(attrs); element.addClass(templater('carousel--*')); return function(scope, element, attrs) { var carousel = new CarouselView(scope, element, attrs); element.data('ons-carousel', carousel); $onsen.registerEventHandlers(carousel, 'postchange refresh overscroll destroy'); $onsen.declareVarAttribute(attrs, carousel); scope.$on('$destroy', function() { carousel._events = undefined; element.data('ons-carousel', undefined); element = null; }); if (element[0].hasAttribute('auto-refresh')) { // Refresh carousel when items are added or removed. scope.$watch( function () { return element[0].childNodes.length; }, function () { setImmediate(function() { carousel.refresh(); }); } ); } setImmediate(function() { carousel.refresh(); }); $onsen.fireComponentEvent(element[0], 'init'); }; }, }; }]); module.directive('onsCarouselItem', ['$onsen', function($onsen) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. scope: false, transclude: false, compile: function(element, attrs) { var templater = $onsen.generateModifierTemplater(attrs); element.addClass(templater('carousel-item--*')); element.css('width', '100%'); return function(scope, element, attrs) { }; }, }; }]); })(); /** * @ngdoc directive * @id col * @name ons-col * @category grid * @description * [en]Represents a column in the grid system. Use with ons-row to layout components.[/en] * [ja]グリッドシステムにて列を定義します。ons-rowとともに使用し、コンポーネントのレイアウトに利用します。[/ja] * @note * [en]For Android 4.3 and earlier, and iOS6 and earlier, when using mixed alignment with ons-row and ons-column, they may not be displayed correctly. You can use only one align.[/en] * [ja]Android 4.3以前、もしくはiOS 6以前のOSの場合、ons-rowとons-columnを組み合わせた場合に描画が崩れる場合があります。[/ja] * @codepen GgujC {wide} * @guide layouting [en]Layouting guide[/en][ja]レイアウト機能[/ja] * @seealso ons-row [en]ons-row component[/en][ja]ons-rowコンポーネント[/ja] * @example * <ons-row> * <ons-col width="50px"><ons-icon icon="fa-twitter"></ons-icon></ons-col> * <ons-col>Text</ons-col> * </ons-row> */ /** * @ngdoc attribute * @name align * @type {String} * @description * [en]Vertical alignment of the column. Valid values are "top", "center", and "bottom".[/en] * [ja]縦の配置を指定する。"top", "center", "bottom"のいずれかを指定します。[/ja] */ /** * @ngdoc attribute * @name width * @type {String} * @description * [en]The width of the column. Valid values are css width values ("10%", "50px").[/en] * [ja]カラムの横幅を指定する。パーセントもしくはピクセルで指定します(10%や50px)。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsCol', ['$timeout', '$onsen', function($timeout, $onsen) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: false, compile: function(element, attrs, transclude) { element.addClass('col ons-col-inner'); return function(scope, element, attrs) { attrs.$observe('align', function(align) { updateAlign(align); }); attrs.$observe('width', function(width) { updateWidth(width); }); // For BC attrs.$observe('size', function(size) { if (!attrs.width) { updateWidth(size); } }); updateAlign(attrs.align); if (attrs.size && !attrs.width) { updateWidth(attrs.size); } else { updateWidth(attrs.width); } $onsen.cleaner.onDestroy(scope, function() { $onsen.clearComponent({ scope: scope, element: element, attrs: attrs }); element = attrs = scope = null; }); function updateAlign(align) { if (align === 'top' || align === 'center' || align === 'bottom') { element.removeClass('col-top col-center col-bottom'); element.addClass('col-' + align); } else { element.removeClass('col-top col-center col-bottom'); } } function updateWidth(width) { if (typeof width === 'string') { width = ('' + width).trim(); width = width.match(/^\d+$/) ? width + '%' : width; element.css({ '-webkit-box-flex': '0', '-webkit-flex': '0 0 ' + width, '-moz-box-flex': '0', '-moz-flex': '0 0 ' + width, '-ms-flex': '0 0 ' + width, 'flex': '0 0 ' + width, 'max-width': width }); } else { element.removeAttr('style'); } } $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id dialog * @name ons-dialog * @category dialog * @description * [en]Dialog that is displayed on top of current screen.[/en] * [ja]現在のスクリーンにダイアログを表示します。[/ja] * @codepen zxxaGa * @guide UsingDialog * [en]Learn how to use the dialog component.[/en] * [ja]ダイアログコンポーネントの使い方[/ja] * @seealso ons-alert-dialog * [en]ons-alert-dialog component[/en] * [ja]ons-alert-dialogコンポーネント[/ja] * @seealso ons-popover * [en]ons-popover component[/en] * [ja]ons-popoverコンポーネント[/ja] * @example * <script> * ons.ready(function() { * ons.createDialog('dialog.html').then(function(dialog) { * dialog.show(); * }); * }); * </script> * * <script type="text/ons-template" id="dialog.html"> * <ons-dialog cancelable> * ... * </ons-dialog> * </script> */ /** * @ngdoc event * @name preshow * @description * [en]Fired just before the dialog is displayed.[/en] * [ja]ダイアログが表示される直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.dialog * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Execute this function to stop the dialog from being shown.[/en] * [ja]この関数を実行すると、ダイアログの表示がキャンセルされます。[/ja] */ /** * @ngdoc event * @name postshow * @description * [en]Fired just after the dialog is displayed.[/en] * [ja]ダイアログが表示された直後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.dialog * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc event * @name prehide * @description * [en]Fired just before the dialog is hidden.[/en] * [ja]ダイアログが隠れる直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.dialog * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Execute this function to stop the dialog from being hidden.[/en] * [ja]この関数を実行すると、ダイアログの非表示がキャンセルされます。[/ja] */ /** * @ngdoc event * @name posthide * @description * [en]Fired just after the dialog is hidden.[/en] * [ja]ダイアログが隠れた後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.dialog * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this dialog.[/en] * [ja]このダイアログを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the dialog.[/en] * [ja]ダイアログの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name cancelable * @description * [en]If this attribute is set the dialog can be closed by tapping the background or by pressing the back button.[/en] * [ja]この属性があると、ダイアログが表示された時に、背景やバックボタンをタップした時にダイアログを閉じます。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set the dialog is disabled.[/en] * [ja]この属性がある時、ダイアログはdisabled状態になります。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @default default * @description * [en]The animation used when showing and hiding the dialog. Can be either "none" or "default".[/en] * [ja]ダイアログを表示する際のアニメーション名を指定します。"none"もしくは"default"を指定できます。[/ja] */ /** * @ngdoc attribute * @name mask-color * @type {String} * @default rgba(0, 0, 0, 0.2) * @description * [en]Color of the background mask. Default is "rgba(0, 0, 0, 0.2)".[/en] * [ja]背景のマスクの色を指定します。"rgba(0, 0, 0, 0.2)"がデフォルト値です。[/ja] */ /** * @ngdoc attribute * @name ons-preshow * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en] * [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-prehide * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en] * [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postshow * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en] * [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-posthide * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en] * [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature show([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none", "fade" and "slide".[/en] * [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定します。[/ja] * @param {Function} [options.callback] * [en]This function is called after the dialog has been revealed.[/en] * [ja]ダイアログが表示され終わった後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Show the dialog.[/en] * [ja]ダイアログを開きます。[/ja] */ /** * @ngdoc method * @signature hide([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none", "fade" and "slide".[/en] * [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定できます。[/ja] * @param {Function} [options.callback] * [en]This functions is called after the dialog has been hidden.[/en] * [ja]ダイアログが隠れた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Hide the dialog.[/en] * [ja]ダイアログを閉じます。[/ja] */ /** * @ngdoc method * @signature isShown() * @description * [en]Returns whether the dialog is visible or not.[/en] * [ja]ダイアログが表示されているかどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is visible.[/en] * [ja]ダイアログが表示されている場合にtrueを返します。[/ja] */ /** * @ngdoc method * @signature destroy() * @description * [en]Destroy the dialog and remove it from the DOM tree.[/en] * [ja]ダイアログを破棄して、DOMツリーから取り除きます。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Retrieve the back button handler for overriding the default behavior.[/en] * [ja]バックボタンハンドラを取得します。デフォルトの挙動を変更することができます。[/ja] */ /** * @ngdoc method * @signature setCancelable(cancelable) * @param {Boolean} cancelable * [en]If true the dialog will be cancelable.[/en] * [ja]ダイアログをキャンセル可能にする場合trueを指定します。[/ja] * @description * [en]Define whether the dialog can be canceled by the user or not.[/en] * [ja]ダイアログを表示した際に、ユーザがそのダイアログをキャンセルできるかどうかを指定します。[/ja] */ /** * @ngdoc method * @signature isCancelable() * @description * [en]Returns whether the dialog is cancelable or not.[/en] * [ja]このダイアログがキャンセル可能かどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is cancelable.[/en] * [ja]ダイアログがキャンセル可能な場合trueを返します。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @description * [en]Disable or enable the dialog.[/en] * [ja]このダイアログをdisabled状態にするかどうかを設定します。[/ja] * @param {Boolean} disabled * [en]If true the dialog will be disabled.[/en] * [ja]trueを指定するとダイアログをdisabled状態になります。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @description * [en]Returns whether the dialog is disabled or enabled.[/en] * [ja]このダイアログがdisabled状態かどうかを返します。[/ja] * @return {Boolean} * [en]true if the dialog is disabled.[/en] * [ja]ダイアログがdisabled状態の場合trueを返します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーが指定されなかった場合には、そのイベントに紐付いているイベントリスナーが全て削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); /** * Dialog directive. */ module.directive('onsDialog', ['$onsen', 'DialogView', function($onsen, DialogView) { return { restrict: 'E', replace: false, scope: true, transclude: true, templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/dialog.tpl', compile: function(element, attrs, transclude) { element[0].setAttribute('no-status-bar-fill', ''); return { pre: function(scope, element, attrs) { transclude(scope, function(clone) { angular.element(element[0].querySelector('.dialog')).append(clone); }); var dialog = new DialogView(scope, element, attrs); scope.modifierTemplater = $onsen.generateModifierTemplater(attrs); $onsen.addModifierMethods(dialog, 'dialog--*', angular.element(element[0].querySelector('.dialog'))); $onsen.declareVarAttribute(attrs, dialog); $onsen.registerEventHandlers(dialog, 'preshow prehide postshow posthide destroy'); element.data('ons-dialog', dialog); scope.$on('$destroy', function() { dialog._events = undefined; $onsen.removeModifierMethods(dialog); element.data('ons-dialog', undefined); element = null; }); }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsDummyForInit', ['$rootScope', function($rootScope) { var isReady = false; return { restrict: 'E', replace: false, link: { post: function(scope, element) { if (!isReady) { isReady = true; $rootScope.$broadcast('$ons-ready'); } element.remove(); } } }; }]); })(); /** * @ngdoc directive * @id gestureDetector * @name ons-gesture-detector * @category input * @description * [en]Component to detect finger gestures within the wrapped element. See the guide for more details.[/en] * [ja]要素内のジェスチャー操作を検知します。詳しくはガイドを参照してください。[/ja] * @guide DetectingFingerGestures * [en]Detecting finger gestures[/en] * [ja]ジェスチャー操作の検知[/ja] * @example * <ons-gesture-detector> * ... * </ons-gesture-detector> */ (function() { 'use strict'; var EVENTS = ('drag dragleft dragright dragup dragdown hold release swipe swipeleft swiperight ' + 'swipeup swipedown tap doubletap touch transform pinch pinchin pinchout rotate').split(/ +/); angular.module('onsen').directive('onsGestureDetector', ['$onsen', function($onsen) { var scopeDef = EVENTS.reduce(function(dict, name) { dict['ng' + titlize(name)] = '&'; return dict; }, {}); return { restrict: 'E', scope: scopeDef, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. replace: false, transclude: true, compile: function(element, attrs) { return function link(scope, element, attrs, controller, transclude) { transclude(scope.$parent, function(cloned) { element.append(cloned); }); var hammer = new Hammer(element[0]); hammer.on(EVENTS.join(' '), handleEvent); $onsen.cleaner.onDestroy(scope, function() { hammer.off(EVENTS.join(' '), handleEvent); $onsen.clearComponent({ scope: scope, element: element, attrs: attrs }); hammer.element = scope = element = attrs = null; }); function handleEvent(event) { var attr = 'ng' + titlize(event.type); if (attr in scopeDef) { scope[attr]({$event: event}); } } $onsen.fireComponentEvent(element[0], 'init'); }; } }; function titlize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } }]); })(); /** * @ngdoc directive * @id icon * @name ons-icon * @category icon * @description * [en]Displays an icon. Font Awesome and Ionicon icons are supported.[/en] * [ja]アイコンを表示するコンポーネントです。Font AwesomeもしくはIoniconsから選択できます。[/ja] * @codepen xAhvg * @guide UsingIcons [en]Using icons[/en][ja]アイコンを使う[/ja] * @example * <ons-icon * icon="fa-twitter" * size="20px" * fixed-width="false" * style="color: red"> * </ons-icon> */ /** * @ngdoc attribute * @name icon * @type {String} * @description * [en]The icon name. <code>fa-</code> prefix for Font Awesome, <code>ion-</code> prefix for Ionicons icons. See all icons at http://fontawesome.io/icons/ and http://ionicons.com.[/en] * [ja]アイコン名を指定します。<code>fa-</code>で始まるものはFont Awesomeとして、<code>ion-</code>で始まるものはIoniconsとして扱われます。使用できるアイコンはこちら: http://fontawesome.io/icons/ および http://ionicons.com。[/ja] */ /** * @ngdoc attribute * @name size * @type {String} * @description * [en]The sizes of the icon. Valid values are lg, 2x, 3x, 4x, 5x, or in pixels.[/en] * [ja]アイコンのサイズを指定します。値は、lg, 2x, 3x, 4x, 5xもしくはピクセル単位で指定できます。[/ja] */ /** * @ngdoc attribute * @name rotate * @type {Number} * @description * [en]Number of degrees to rotate the icon. Valid values are 90, 180, or 270.[/en] * [ja]アイコンを回転して表示します。90, 180, 270から指定できます。[/ja] */ /** * @ngdoc attribute * @name flip * @type {String} * @description * [en]Flip the icon. Valid values are "horizontal" and "vertical".[/en] * [ja]アイコンを反転します。horizontalもしくはverticalを指定できます。[/ja] */ /** * @ngdoc attribute * @name fixed-width * @type {Boolean} * @default false * @description * [en]When used in the list, you want the icons to have the same width so that they align vertically by setting the value to true. Valid values are true, false. Default is false.[/en] * [ja]等幅にするかどうかを指定します。trueもしくはfalseを指定できます。デフォルトはfalseです。[/ja] */ /** * @ngdoc attribute * @name spin * @type {Boolean} * @default false * @description * [en]Specify whether the icon should be spinning. Valid values are true and false.[/en] * [ja]アイコンを回転するかどうかを指定します。trueもしくはfalseを指定できます。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); function cleanClassAttribute(element) { var classList = ('' + element.attr('class')).split(/ +/).filter(function(classString) { return classString !== 'fa' && classString.substring(0, 3) !== 'fa-' && classString.substring(0, 4) !== 'ion-'; }); element.attr('class', classList.join(' ')); } function buildClassAndStyle(attrs) { var classList = ['ons-icon']; var style = {}; // icon if (attrs.icon.indexOf('ion-') === 0) { classList.push(attrs.icon); classList.push('ons-icon--ion'); } else if (attrs.icon.indexOf('fa-') === 0) { classList.push(attrs.icon); classList.push('fa'); } else { classList.push('fa'); classList.push('fa-' + attrs.icon); } // size var size = '' + attrs.size; if (size.match(/^[1-5]x|lg$/)) { classList.push('fa-' + size); } else if (typeof attrs.size === 'string') { style['font-size'] = size; } else { classList.push('fa-lg'); } return { 'class': classList.join(' '), 'style': style }; } module.directive('onsIcon', ['$onsen', function($onsen) { return { restrict: 'E', replace: false, transclude: false, link: function(scope, element, attrs) { if (attrs.ngController) { throw new Error('This element can\'t accept ng-controller directive.'); } var update = function() { cleanClassAttribute(element); var builded = buildClassAndStyle(attrs); element.css(builded.style); element.addClass(builded['class']); }; var builded = buildClassAndStyle(attrs); element.css(builded.style); element.addClass(builded['class']); attrs.$observe('icon', update); attrs.$observe('size', update); attrs.$observe('fixedWidth', update); attrs.$observe('rotate', update); attrs.$observe('flip', update); attrs.$observe('spin', update); $onsen.cleaner.onDestroy(scope, function() { $onsen.clearComponent({ scope: scope, element: element, attrs: attrs }); element = scope = attrs = null; }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id if-orientation * @name ons-if-orientation * @category util * @description * [en]Conditionally display content depending on screen orientation. Valid values are portrait and landscape. Different from other components, this component is used as attribute in any element.[/en] * [ja]画面の向きに応じてコンテンツの制御を行います。portraitもしくはlandscapeを指定できます。すべての要素の属性に使用できます。[/ja] * @seealso ons-if-platform [en]ons-if-platform component[/en][ja]ons-if-platformコンポーネント[/ja] * @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja] * @example * <div ons-if-orientation="portrait"> * <p>This will only be visible in portrait mode.</p> * </div> */ /** * @ngdoc attribute * @name ons-if-orientation * @type {String} * @description * [en]Either "portrait" or "landscape".[/en] * [ja]portraitもしくはlandscapeを指定します。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsIfOrientation', ['$onsen', '$onsGlobal', function($onsen, $onsGlobal) { return { restrict: 'A', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: false, compile: function(element) { element.css('display', 'none'); return function(scope, element, attrs) { element.addClass('ons-if-orientation-inner'); attrs.$observe('onsIfOrientation', update); $onsGlobal.orientation.on('change', update); update(); $onsen.cleaner.onDestroy(scope, function() { $onsGlobal.orientation.off('change', update); $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); element = scope = attrs = null; }); function update() { var userOrientation = ('' + attrs.onsIfOrientation).toLowerCase(); var orientation = getLandscapeOrPortrait(); if (userOrientation === 'portrait' || userOrientation === 'landscape') { if (userOrientation === orientation) { element.css('display', ''); } else { element.css('display', 'none'); } } } function getLandscapeOrPortrait() { return $onsGlobal.orientation.isPortrait() ? 'portrait' : 'landscape'; } }; } }; }]); })(); /** * @ngdoc directive * @id if-platform * @name ons-if-platform * @category util * @description * [en]Conditionally display content depending on the platform / browser. Valid values are "ios", "android", "blackberry", "chrome", "safari", "firefox", and "opera".[/en] * [ja]プラットフォームやブラウザーに応じてコンテンツの制御をおこないます。ios, android, blackberry, chrome, safari, firefox, operaを指定できます。[/ja] * @seealso ons-if-orientation [en]ons-if-orientation component[/en][ja]ons-if-orientationコンポーネント[/ja] * @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja] * @example * <div ons-if-platform="android"> * ... * </div> */ /** * @ngdoc attribute * @name ons-if-platform * @type {String} * @description * [en]Either "opera", "firefox", "safari", "chrome", "ie", "android", "blackberry", "ios" or "windows".[/en] * [ja]"opera", "firefox", "safari", "chrome", "ie", "android", "blackberry", "ios", "windows"のいずれかを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsIfPlatform', ['$onsen', function($onsen) { return { restrict: 'A', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: false, compile: function(element) { element.addClass('ons-if-platform-inner'); element.css('display', 'none'); var platform = getPlatformString(); return function(scope, element, attrs) { attrs.$observe('onsIfPlatform', function(userPlatform) { if (userPlatform) { update(); } }); update(); $onsen.cleaner.onDestroy(scope, function() { $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); element = scope = attrs = null; }); function update() { if (attrs.onsIfPlatform.toLowerCase() === platform.toLowerCase()) { element.css('display', 'block'); } else { element.css('display', 'none'); } } }; function getPlatformString() { if (navigator.userAgent.match(/Android/i)) { return 'android'; } if ((navigator.userAgent.match(/BlackBerry/i)) || (navigator.userAgent.match(/RIM Tablet OS/i)) || (navigator.userAgent.match(/BB10/i))) { return 'blackberry'; } if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) { return 'ios'; } if (navigator.userAgent.match(/IEMobile/i)) { return 'windows'; } // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera) var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; if (isOpera) { return 'opera'; } var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+ if (isFirefox) { return 'firefox'; } var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; // At least Safari 3+: "[object HTMLElementConstructor]" if (isSafari) { return 'safari'; } var isChrome = !!window.chrome && !isOpera; // Chrome 1+ if (isChrome) { return 'chrome'; } var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6 if (isIE) { return 'ie'; } return 'unknown'; } } }; }]); })(); /** * @ngdoc directive * @id ons-keyboard-active * @name ons-keyboard-active * @category input * @description * [en] * Conditionally display content depending on if the software keyboard is visible or hidden. * This component requires cordova and that the com.ionic.keyboard plugin is installed. * [/en] * [ja] * ソフトウェアキーボードが表示されているかどうかで、コンテンツを表示するかどうかを切り替えることが出来ます。 * このコンポーネントは、Cordovaやcom.ionic.keyboardプラグインを必要とします。 * [/ja] * @guide UtilityAPIs * [en]Other utility APIs[/en] * [ja]他のユーティリティAPI[/ja] * @example * <div ons-keyboard-active> * This will only be displayed if the software keyboard is open. * </div> * <div ons-keyboard-inactive> * There is also a component that does the opposite. * </div> */ /** * @ngdoc attribute * @name ons-keyboard-active * @description * [en]The content of tags with this attribute will be visible when the software keyboard is open.[/en] * [ja]この属性がついた要素は、ソフトウェアキーボードが表示された時に初めて表示されます。[/ja] */ /** * @ngdoc attribute * @name ons-keyboard-inactive * @description * [en]The content of tags with this attribute will be visible when the software keyboard is hidden.[/en] * [ja]この属性がついた要素は、ソフトウェアキーボードが隠れている時のみ表示されます。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); var compileFunction = function(show, $onsen) { return function(element) { return function(scope, element, attrs) { var dispShow = show ? 'block' : 'none', dispHide = show ? 'none' : 'block'; var onShow = function() { element.css('display', dispShow); }; var onHide = function() { element.css('display', dispHide); }; var onInit = function(e) { if (e.visible) { onShow(); } else { onHide(); } }; ons.softwareKeyboard.on('show', onShow); ons.softwareKeyboard.on('hide', onHide); ons.softwareKeyboard.on('init', onInit); if (ons.softwareKeyboard._visible) { onShow(); } else { onHide(); } $onsen.cleaner.onDestroy(scope, function() { ons.softwareKeyboard.off('show', onShow); ons.softwareKeyboard.off('hide', onHide); ons.softwareKeyboard.off('init', onInit); $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); element = scope = attrs = null; }); }; }; }; module.directive('onsKeyboardActive', ['$onsen', function($onsen) { return { restrict: 'A', replace: false, transclude: false, scope: false, compile: compileFunction(true, $onsen) }; }]); module.directive('onsKeyboardInactive', ['$onsen', function($onsen) { return { restrict: 'A', replace: false, transclude: false, scope: false, compile: compileFunction(false, $onsen) }; }]); })(); /** * @ngdoc directive * @id lazy-repeat * @name ons-lazy-repeat * @category control * @description * [en] * Using this component a list with millions of items can be rendered without a drop in performance. * It does that by "lazily" loading elements into the DOM when they come into view and * removing items from the DOM when they are not visible. * [/en] * [ja] * このコンポーネント内で描画されるアイテムのDOM要素の読み込みは、画面に見えそうになった時まで自動的に遅延され、 * 画面から見えなくなった場合にはその要素は動的にアンロードされます。 * このコンポーネントを使うことで、パフォーマンスを劣化させること無しに巨大な数の要素を描画できます。 * [/ja] * @codepen QwrGBm * @guide UsingLazyRepeat * [en]How to use Lazy Repeat[/en] * [ja]レイジーリピートの使い方[/ja] * @example * <script> * ons.bootstrap() * * .controller('MyController', function($scope) { * $scope.MyDelegate = { * countItems: function() { * // Return number of items. * return 1000000; * }, * * calculateItemHeight: function(index) { * // Return the height of an item in pixels. * return 45; * }, * * configureItemScope: function(index, itemScope) { * // Initialize scope * itemScope.item = 'Item #' + (index + 1); * }, * * destroyItemScope: function(index, itemScope) { * // Optional method that is called when an item is unloaded. * console.log('Destroyed item with index: ' + index); * } * }; * }); * </script> * * <ons-list ng-controller="MyController"> * <ons-list-item ons-lazy-repeat="MyDelegate"> * {{ item }} * </ons-list-item> * </ons-list> */ /** * @ngdoc attribute * @name ons-lazy-repeat * @type {Expression} * @description * [en]A delegate object, can be either an object attached to the scope (when using AngularJS) or a normal JavaScript variable.[/en] * [ja]要素のロード、アンロードなどの処理を委譲するオブジェクトを指定します。AngularJSのスコープの変数名や、通常のJavaScriptの変数名を指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); /** * Lazy repeat directive. */ module.directive('onsLazyRepeat', ['$onsen', 'LazyRepeatView', function($onsen, LazyRepeatView) { return { restrict: 'A', replace: false, priority: 1000, transclude: 'element', compile: function(element, attrs, linker) { return function(scope, element, attrs) { var lazyRepeat = new LazyRepeatView(scope, element, attrs, linker); scope.$on('$destroy', function() { scope = element = attrs = linker = null; }); }; } }; }]); })(); /** * @ngdoc directive * @id list * @name ons-list * @category list * @modifier inset * [en]Inset list that doesn't cover the whole width of the parent.[/en] * [ja]親要素の画面いっぱいに広がらないリストを表示します。[/ja] * @modifier noborder * [en]A list with no borders at the top and bottom.[/en] * [ja]リストの上下のボーダーが無いリストを表示します。[/ja] * @description * [en]Component to define a list, and the container for ons-list-item(s).[/en] * [ja]リストを表現するためのコンポーネント。ons-list-itemのコンテナとして使用します。[/ja] * @seealso ons-list-item * [en]ons-list-item component[/en] * [ja]ons-list-itemコンポーネント[/ja] * @seealso ons-list-header * [en]ons-list-header component[/en] * [ja]ons-list-headerコンポーネント[/ja] * @guide UsingList * [en]Using lists[/en] * [ja]リストを使う[/ja] * @codepen yxcCt * @example * <ons-list> * <ons-list-header>Header Text</ons-list-header> * <ons-list-item>Item</ons-list-item> * <ons-list-item>Item</ons-list-item> * </ons-list> */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the list.[/en] * [ja]リストの表現を指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsList', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', scope: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. replace: false, transclude: false, compile: function(element, attrs) { return function(scope, element, attrs) { var list = new GenericView(scope, element, attrs); $onsen.declareVarAttribute(attrs, list); element.data('ons-list', list); scope.$on('$destroy', function() { list._events = undefined; $onsen.removeModifierMethods(list); element.data('ons-list', undefined); element = null; }); var templater = $onsen.generateModifierTemplater(attrs); element.addClass('list ons-list-inner'); element.addClass(templater('list--*')); $onsen.addModifierMethods(list, 'list--*', element); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id list-header * @name ons-list-header * @category list * @description * [en]Header element for list items. Must be put inside ons-list component.[/en] * [ja]リスト要素に使用するヘッダー用コンポーネント。ons-listと共に使用します。[/ja] * @seealso ons-list * [en]ons-list component[/en] * [ja]ons-listコンポーネント[/ja] * @seealso ons-list-item [en]ons-list-item component[/en][ja]ons-list-itemコンポーネント[/ja] * @guide UsingList [en]Using lists[/en][ja]リストを使う[/ja] * @codepen yxcCt * @example * <ons-list> * <ons-list-header>Header Text</ons-list-header> * <ons-list-item>Item</ons-list-item> * <ons-list-item>Item</ons-list-item> * </ons-list> */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the list header.[/en] * [ja]ヘッダーの表現を指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsListHeader', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. replace: false, transclude: false, compile: function() { return function(scope, element, attrs) { var listHeader = new GenericView(scope, element, attrs); $onsen.declareVarAttribute(attrs, listHeader); element.data('ons-listHeader', listHeader); scope.$on('$destroy', function() { listHeader._events = undefined; $onsen.removeModifierMethods(listHeader); element.data('ons-listHeader', undefined); element = null; }); var templater = $onsen.generateModifierTemplater(attrs); element.addClass('list__header ons-list-header-inner'); element.addClass(templater('list__header--*')); $onsen.addModifierMethods(listHeader, 'list__header--*', element); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id list-item * @name ons-list-item * @category list * @modifier tappable * [en]Made the list item change appearance when it's tapped.[/en] * [ja]タップやクリックした時に効果が表示されるようになります。[/ja] * @modifier chevron * [en]Display a chevron at the right end of the list item and make it change appearance when tapped.[/en] * [ja]要素の右側に右矢印が表示されます。また、タップやクリックした時に効果が表示されるようになります。[/ja] * @description * [en]Component that represents each item in the list. Must be put inside the ons-list component.[/en] * [ja]リストの各要素を表現するためのコンポーネントです。ons-listコンポーネントと共に使用します。[/ja] * @seealso ons-list * [en]ons-list component[/en] * [ja]ons-listコンポーネント[/ja] * @seealso ons-list-header * [en]ons-list-header component[/en] * [ja]ons-list-headerコンポーネント[/ja] * @guide UsingList * [en]Using lists[/en] * [ja]リストを使う[/ja] * @codepen yxcCt * @example * <ons-list> * <ons-list-header>Header Text</ons-list-header> * <ons-list-item>Item</ons-list-item> * <ons-list-item>Item</ons-list-item> * </ons-list> */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the list item.[/en] * [ja]各要素の表現を指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsListItem', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. replace: false, transclude: false, compile: function() { return function(scope, element, attrs) { var listItem = new GenericView(scope, element, attrs); $onsen.declareVarAttribute(attrs, listItem); element.data('ons-list-item', listItem); scope.$on('$destroy', function() { listItem._events = undefined; $onsen.removeModifierMethods(listItem); element.data('ons-list-item', undefined); element = null; }); var templater = $onsen.generateModifierTemplater(attrs); element.addClass('list__item ons-list-item-inner'); element.addClass(templater('list__item--*')); $onsen.addModifierMethods(listItem, 'list__item--*', element); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id loading-placeholder * @name ons-loading-placeholder * @category util * @description * [en]Display a placeholder while the content is loading.[/en] * [ja]Onsen UIが読み込まれるまでに表示するプレースホルダーを表現します。[/ja] * @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja] * @example * <div ons-loading-placeholder="page.html"> * Loading... * </div> */ /** * @ngdoc attribute * @name ons-loading-placeholder * @type {String} * @description * [en]The url of the page to load.[/en] * [ja]読み込むページのURLを指定します。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsLoadingPlaceholder', ['$onsen', '$compile', function($onsen, $compile) { return { restrict: 'A', replace: false, transclude: false, scope: false, link: function(scope, element, attrs) { if (!attrs.onsLoadingPlaceholder.length) { throw Error('Must define page to load.'); } setImmediate(function() { $onsen.getPageHTMLAsync(attrs.onsLoadingPlaceholder).then(function(html) { // Remove page tag. html = html .trim() .replace(/^<ons-page>/, '') .replace(/<\/ons-page>$/, ''); var div = document.createElement('div'); div.innerHTML = html; var newElement = angular.element(div); newElement.css('display', 'none'); element.append(newElement); $compile(newElement)(scope); for (var i = element[0].childNodes.length - 1; i >= 0; i--){ var e = element[0].childNodes[i]; if (e !== div) { element[0].removeChild(e); } } newElement.css('display', 'block'); }); }); } }; }]); })(); /** * @ngdoc directive * @id modal * @name ons-modal * @category modal * @description * [en] * Modal component that masks current screen. * Underlying components are not subject to any events while the modal component is shown. * [/en] * [ja] * 画面全体をマスクするモーダル用コンポーネントです。下側にあるコンポーネントは、 * モーダルが表示されている間はイベント通知が行われません。 * [/ja] * @guide UsingModal * [en]Using ons-modal component[/en] * [ja]モーダルの使い方[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @codepen devIg * @example * <ons-modal> * ... * </ons-modal> */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this modal.[/en] * [ja]このモーダルを参照するための名前を指定します。[/ja] */ /** * @ngdoc method * @signature toggle() * @description * [en]Toggle modal visibility.[/en] * [ja]モーダルの表示を切り替えます。[/ja] */ /** * @ngdoc method * @signature show() * @description * [en]Show modal.[/en] * [ja]モーダルを表示します。[/ja] */ /** * @ngdoc method * @signature hide() * @description * [en]Hide modal.[/en] * [ja]モーダルを非表示にします。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Retrieve the back button handler.[/en] * [ja]ons-modalに紐付いているバックボタンハンドラを取得します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); /** * Modal directive. */ module.directive('onsModal', ['$onsen', 'ModalView', function($onsen, ModalView) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclde. scope: false, transclude: false, compile: function(element, attrs) { compile(element, attrs); return { pre: function(scope, element, attrs) { var page = element.inheritedData('ons-page'); if (page) { page.registerExtraElement(element); } var modal = new ModalView(scope, element); $onsen.addModifierMethods(modal, 'modal--*', element); $onsen.addModifierMethods(modal, 'modal--*__content', element.children()); $onsen.declareVarAttribute(attrs, modal); element.data('ons-modal', modal); scope.$on('$destroy', function() { modal._events = undefined; $onsen.removeModifierMethods(modal); element.data('ons-modal', undefined); }); }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; function compile(element, attrs) { var modifierTemplater = $onsen.generateModifierTemplater(attrs); var html = element[0].innerHTML; element[0].innerHTML = ''; var wrapper = angular.element('<div></div>'); wrapper.addClass('modal__content'); wrapper.addClass(modifierTemplater('modal--*__content')); element.css('display', 'none'); element.addClass('modal'); element.addClass(modifierTemplater('modal--*')); wrapper[0].innerHTML = html; element.append(wrapper); } }]); })(); /** * @ngdoc directive * @id navigator * @name ons-navigator * @category navigation * @description * [en]A component that provides page stack management and navigation. This component does not have a visible content.[/en] * [ja]ページスタックの管理とナビゲーション機能を提供するコンポーネント。画面上への出力はありません。[/ja] * @codepen yrhtv * @guide PageNavigation * [en]Guide for page navigation[/en] * [ja]ページナビゲーションの概要[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @guide EventHandling * [en]Event handling descriptions[/en] * [ja]イベント処理の使い方[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @seealso ons-toolbar * [en]ons-toolbar component[/en] * [ja]ons-toolbarコンポーネント[/ja] * @seealso ons-back-button * [en]ons-back-button component[/en] * [ja]ons-back-buttonコンポーネント[/ja] * @example * <ons-navigator animation="slide" var="app.navi"> * <ons-page> * <ons-toolbar> * <div class="center">Title</div> * </ons-toolbar> * * <p style="text-align: center"> * <ons-button modifier="light" ng-click="app.navi.pushPage('page.html');">Push</ons-button> * </p> * </ons-page> * </ons-navigator> * * <ons-template id="page.html"> * <ons-page> * <ons-toolbar> * <div class="center">Title</div> * </ons-toolbar> * * <p style="text-align: center"> * <ons-button modifier="light" ng-click="app.navi.popPage('page.html');">Pop</ons-button> * </p> * </ons-page> * </ons-template> */ /** * @ngdoc event * @name prepush * @description * [en]Fired just before a page is pushed.[/en] * [ja]pageがpushされる直前に発火されます。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.navigator * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Object} event.currentPage * [en]Current page object.[/en] * [ja]現在のpageオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call this function to cancel the push.[/en] * [ja]この関数を呼び出すと、push処理がキャンセルされます。[/ja] */ /** * @ngdoc event * @name prepop * @description * [en]Fired just before a page is popped.[/en] * [ja]pageがpopされる直前に発火されます。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.navigator * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Object} event.currentPage * [en]Current page object.[/en] * [ja]現在のpageオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call this function to cancel the pop.[/en] * [ja]この関数を呼び出すと、pageのpopがキャンセルされます。[/ja] */ /** * @ngdoc event * @name postpush * @description * [en]Fired just after a page is pushed.[/en] * [ja]pageがpushされてアニメーションが終了してから発火されます。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.navigator * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Object} event.enterPage * [en]Object of the next page.[/en] * [ja]pushされたpageオブジェクト。[/ja] * @param {Object} event.leavePage * [en]Object of the previous page.[/en] * [ja]以前のpageオブジェクト。[/ja] */ /** * @ngdoc event * @name postpop * @description * [en]Fired just after a page is popped.[/en] * [ja]pageがpopされてアニメーションが終わった後に発火されます。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.navigator * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Object} event.enterPage * [en]Object of the next page.[/en] * [ja]popされて表示されるページのオブジェクト。[/ja] * @param {Object} event.leavePage * [en]Object of the previous page.[/en] * [ja]popされて消えるページのオブジェクト。[/ja] */ /** * @ngdoc attribute * @name page * @type {String} * @description * [en]First page to show when navigator is initialized.[/en] * [ja]ナビゲーターが初期化された時に表示するページを指定します。[/ja] */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this navigator.[/en] * [ja]このナビゲーターを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name ons-prepush * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prepush" event is fired.[/en] * [ja]"prepush"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-prepop * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prepop" event is fired.[/en] * [ja]"prepop"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postpush * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postpush" event is fired.[/en] * [ja]"postpush"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postpop * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postpop" event is fired.[/en] * [ja]"postpop"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature pushPage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either a HTML document or a <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定します。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @param {Function} [options.onTransitionEnd] * [en]Function that is called when the transition has ended.[/en] * [ja]pushPage()による画面遷移が終了した時に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Pushes the specified pageUrl into the page stack.[/en] * [ja]指定したpageUrlを新しいページスタックに追加します。新しいページが表示されます。[/ja] */ /** * @ngdoc method * @signature insertPage(index, pageUrl, [options]) * @param {Number} index * [en]The index where it should be inserted.[/en] * [ja]スタックに挿入する位置のインデックスを指定します。[/ja] * @param {String} pageUrl * [en]Page URL. Can be either a HTML document or a <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定します。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @description * [en]Insert the specified pageUrl into the page stack with specified index.[/en] * [ja]指定したpageUrlをページスタックのindexで指定した位置に追加します。[/ja] */ /** * @ngdoc method * @signature popPage([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定します。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @param {Function} [options.onTransitionEnd] * [en]Function that is called when the transition has ended.[/en] * [ja]このメソッドによる画面遷移が終了した際に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Pops the current page from the page stack. The previous page will be displayed.[/en] * [ja]現在表示中のページをページスタックから取り除きます。一つ前のページに戻ります。[/ja] */ /** * @ngdoc method * @signature replacePage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either a HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定できます。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @param {Function} [options.onTransitionEnd] * [en]Function that is called when the transition has ended.[/en] * [ja]このメソッドによる画面遷移が終了した際に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Replaces the current page with the specified one.[/en] * [ja]現在表示中のページをを指定したページに置き換えます。[/ja] */ /** * @ngdoc method * @signature resetToPage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either a HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en] * [ja]アニメーション名を指定できます。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja] * @param {Function} [options.onTransitionEnd] * [en]Function that is called when the transition has ended.[/en] * [ja]このメソッドによる画面遷移が終了した際に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Clears page stack and adds the specified pageUrl to the page stack.[/en] * [ja]ページスタックをリセットし、指定したページを表示します。[/ja] */ /** * @ngdoc method * @signature getCurrentPage() * @return {Object} * [en]Current page object.[/en] * [ja]現在のpageオブジェクト。[/ja] * @description * [en]Get current page's navigator item. Use this method to access options passed by pushPage() or resetToPage() method.[/en] * [ja]現在のページを取得します。pushPage()やresetToPage()メソッドの引数を取得できます。[/ja] */ /** * @ngdoc method * @signature getPages() * @return {List} * [en]List of page objects.[/en] * [ja]pageオブジェクトの配列。[/ja] * @description * [en]Retrieve the entire page stack of the navigator.[/en] * [ja]ナビゲーターの持つページスタックの一覧を取得します。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Retrieve the back button handler for overriding the default behavior.[/en] * [ja]バックボタンハンドラを取得します。デフォルトの挙動を変更することができます。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsNavigator', ['$compile', 'NavigatorView', '$onsen', function($compile, NavigatorView, $onsen) { return { restrict: 'E', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: true, compile: function(element) { var html = $onsen.normalizePageHTML(element.html()); element.contents().remove(); return { pre: function(scope, element, attrs, controller) { var navigator = new NavigatorView(scope, element, attrs); $onsen.declareVarAttribute(attrs, navigator); $onsen.registerEventHandlers(navigator, 'prepush prepop postpush postpop destroy'); if (attrs.page) { navigator.pushPage(attrs.page, {}); } else { var pageScope = navigator._createPageScope(); var pageElement = angular.element(html); var linkScope = $compile(pageElement); var link = function() { linkScope(pageScope); }; navigator._pushPageDOM('', pageElement, link, pageScope, {}); pageElement = null; } element.data('ons-navigator', navigator); element.data('_scope', scope); scope.$on('$destroy', function() { element.data('_scope', undefined); navigator._events = undefined; element.data('ons-navigator', undefined); element = null; }); }, post: function(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id page * @name ons-page * @category base * @description * [en]Should be used as root component of each page. The content inside page component is scrollable.[/en] * [ja]ページ定義のためのコンポーネントです。このコンポーネントの内容はスクロールが許可されます。[/ja] * @guide ManagingMultiplePages * [en]Managing multiple pages[/en] * [ja]複数のページを管理する[/ja] * @guide Pageinitevent * [en]Event for page initialization[/en] * [ja]ページ初期化のイベント[/ja] * @guide HandlingBackButton * [en]Handling back button[/en] * [ja]バックボタンに対応する[/ja] * @guide OverridingCSSstyles * [en]Overriding CSS styles[/en] * [ja]CSSスタイルのオーバーライド[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @example * <ons-page> * <ons-toolbar> * <div class="center">Title</div> * </ons-toolbar> * * ... * </ons-page> */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this page.[/en] * [ja]このページを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]Specify modifier name to specify custom styles.[/en] * [ja]スタイル定義をカスタマイズするための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name on-device-backbutton * @type {Expression} * @description * [en]Allows you to specify custom behavior when the back button is pressed.[/en] * [ja]デバイスのバックボタンが押された時の挙動を設定できます。[/ja] */ /** * @ngdoc attribute * @name ng-device-backbutton * @type {Expression} * @description * [en]Allows you to specify custom behavior with an AngularJS expression when the back button is pressed.[/en] * [ja]デバイスのバックボタンが押された時の挙動を設定できます。AngularJSのexpressionを指定できます。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Get the associated back button handler. This method may return null if no handler is assigned.[/en] * [ja]バックボタンハンドラを取得します。このメソッドはnullを返す場合があります。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsPage', ['$onsen', 'PageView', function($onsen, PageView) { function firePageInitEvent(element) { // TODO: remove dirty fix var i = 0; var f = function() { if (i++ < 5) { if (isAttached(element)) { fillStatusBar(element); $onsen.fireComponentEvent(element, 'init'); fireActualPageInitEvent(element); } else { setImmediate(f); } } else { throw new Error('Fail to fire "pageinit" event. Attach "ons-page" element to the document after initialization.'); } }; f(); } function fireActualPageInitEvent(element) { var event = document.createEvent('HTMLEvents'); event.initEvent('pageinit', true, true); element.dispatchEvent(event); } function fillStatusBar(element) { if ($onsen.shouldFillStatusBar(element)) { // Adjustments for IOS7 var fill = angular.element(document.createElement('div')); fill.addClass('page__status-bar-fill'); fill.css({width: '0px', height: '0px'}); angular.element(element).prepend(fill); } } function isAttached(element) { if (document.documentElement === element) { return true; } return element.parentNode ? isAttached(element.parentNode) : false; } function preLink(scope, element, attrs, controller, transclude) { var page = new PageView(scope, element, attrs); $onsen.declareVarAttribute(attrs, page); element.data('ons-page', page); var modifierTemplater = $onsen.generateModifierTemplater(attrs), template = 'page--*'; element.addClass('page ' + modifierTemplater(template)); $onsen.addModifierMethods(page, template, element); var pageContent = angular.element(element[0].querySelector('.page__content')); pageContent.addClass(modifierTemplater('page--*__content')); pageContent = null; var pageBackground = angular.element(element[0].querySelector('.page__background')); pageBackground.addClass(modifierTemplater('page--*__background')); pageBackground = null; element.data('_scope', scope); $onsen.cleaner.onDestroy(scope, function() { element.data('_scope', undefined); page._events = undefined; $onsen.removeModifierMethods(page); element.data('ons-page', undefined); $onsen.clearComponent({ element: element, scope: scope, attrs: attrs }); scope = element = attrs = null; }); } function postLink(scope, element, attrs) { firePageInitEvent(element[0]); } return { restrict: 'E', // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclde. transclude: false, scope: false, compile: function(element) { var children = element.children().remove(); var content = angular.element('<div class="page__content ons-page-inner"></div>').append(children); var background = angular.element('<div class="page__background"></div>'); if (element.attr('style')) { background.attr('style', element.attr('style')); element.attr('style', ''); } element.append(background); if (Modernizr.csstransforms3d) { element.append(content); } else { content.css('overflow', 'visible'); var wrapper = angular.element('<div></div>'); wrapper.append(children); content.append(wrapper); element.append(content); wrapper = null; // IScroll for Android2 var scroller = new IScroll(content[0], { momentum: true, bounce: true, hScrollbar: false, vScrollbar: false, preventDefault: false }); var offset = 10; scroller.on('scrollStart', function(e) { var scrolled = scroller.y - offset; if (scrolled < (scroller.maxScrollY + 40)) { // TODO: find a better way to know when content is upated so we can refresh scroller.refresh(); } }); } content = null; background = null; children = null; return { pre: preLink, post: postLink }; } }; }]); })(); /** * @ngdoc directive * @id popover * @name ons-popover * @category popover * @modifier android * [en]Display an Android style popover.[/en] * [ja]Androidライクなポップオーバーを表示します。[/ja] * @description * [en]A component that displays a popover next to an element.[/en] * [ja]ある要素を対象とするポップオーバーを表示するコンポーネントです。[/ja] * @codepen ZYYRKo * @example * <script> * ons.ready(function() { * ons.createPopover('popover.html').then(function(popover) { * popover.show('#mybutton'); * }); * }); * </script> * * <script type="text/ons-template" id="popover.html"> * <ons-popover cancelable> * <p style="text-align: center; opacity: 0.5;">This popover will choose which side it's displayed on automatically.</p> * </ons-popover> * </script> */ /** * @ngdoc event * @name preshow * @description * [en]Fired just before the popover is displayed.[/en] * [ja]ポップオーバーが表示される直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.popover * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call this function to stop the popover from being shown.[/en] * [ja]この関数を呼び出すと、ポップオーバーの表示がキャンセルされます。[/ja] */ /** * @ngdoc event * @name postshow * @description * [en]Fired just after the popover is displayed.[/en] * [ja]ポップオーバーが表示された直後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.popover * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc event * @name prehide * @description * [en]Fired just before the popover is hidden.[/en] * [ja]ポップオーバーが隠れる直前に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.popover * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call this function to stop the popover from being hidden.[/en] * [ja]この関数を呼び出すと、ポップオーバーが隠れる処理をキャンセルします。[/ja] */ /** * @ngdoc event * @name posthide * @description * [en]Fired just after the popover is hidden.[/en] * [ja]ポップオーバーが隠れた後に発火します。[/ja] * @param {Object} event [en]Event object.[/en] * @param {Object} event.popover * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this popover.[/en] * [ja]このポップオーバーを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the popover.[/en] * [ja]ポップオーバーの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name direction * @type {String} * @description * [en] * A space separated list of directions. If more than one direction is specified, * it will be chosen automatically. Valid directions are "up", "down", "left" and "right". * [/en] * [ja] * ポップオーバーを表示する方向を空白区切りで複数指定できます。 * 指定できる方向は、"up", "down", "left", "right"の4つです。空白区切りで複数指定することもできます。 * 複数指定された場合、対象とする要素に合わせて指定した値から自動的に選択されます。 * [/ja] */ /** * @ngdoc attribute * @name cancelable * @description * [en]If this attribute is set the popover can be closed by tapping the background or by pressing the back button.[/en] * [ja]この属性があると、ポップオーバーが表示された時に、背景やバックボタンをタップした時にをポップオーバー閉じます。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set the popover is disabled.[/en] * [ja]この属性がある時、ポップオーバーはdisabled状態になります。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @description * [en]The animation used when showing an hiding the popover. Can be either "none" or "fade".[/en] * [ja]ポップオーバーを表示する際のアニメーション名を指定します。[/ja] */ /** * @ngdoc attribute * @name mask-color * @type {Color} * @description * [en]Color of the background mask. Default is "rgba(0, 0, 0, 0.2)".[/en] * [ja]背景のマスクの色を指定します。デフォルトは"rgba(0, 0, 0, 0.2)"です。[/ja] */ /** * @ngdoc attribute * @name ons-preshow * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en] * [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-prehide * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en] * [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postshow * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en] * [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-posthide * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en] * [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature show(target, [options]) * @param {String|Event|HTMLElement} target * [en]Target element. Can be either a CSS selector, an event object or a DOM element.[/en] * [ja]ポップオーバーのターゲットとなる要素を指定します。CSSセレクタかeventオブジェクトかDOM要素のいずれかを渡せます。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "fade" and "none".[/en] * [ja]アニメーション名を指定します。"fade"もしくは"none"を指定できます。[/ja] * @description * [en]Open the popover and point it at a target. The target can be either an event, a css selector or a DOM element..[/en] * [ja]対象とする要素にポップオーバーを表示します。target引数には、$eventオブジェクトやDOMエレメントやCSSセレクタを渡すことが出来ます。[/ja] */ /** * @ngdoc method * @signature hide([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "fade" and "none".[/en] * [ja]アニメーション名を指定します。"fade"もしくは"none"を指定できます。[/ja] * @description * [en]Close the popover.[/en] * [ja]ポップオーバーを閉じます。[/ja] */ /** * @ngdoc method * @signature isShown() * @return {Boolean} * [en]true if the popover is visible.[/en] * [ja]ポップオーバーが表示されている場合にtrueとなります。[/ja] * @description * [en]Returns whether the popover is visible or not.[/en] * [ja]ポップオーバーが表示されているかどうかを返します。[/ja] */ /** * @ngdoc method * @signature destroy() * @description * [en]Destroy the popover and remove it from the DOM tree.[/en] * [ja]ポップオーバーを破棄して、DOMツリーから取り除きます。[/ja] */ /** * @ngdoc method * @signature setCancelable(cancelable) * @param {Boolean} cancelable * [en]If true the popover will be cancelable.[/en] * [ja]ポップオーバーがキャンセル可能にしたい場合にtrueを指定します。[/ja] * @description * [en]Set whether the popover can be canceled by the user when it is shown.[/en] * [ja]ポップオーバーを表示した際に、ユーザがそのポップオーバーをキャンセルできるかどうかを指定します。[/ja] */ /** * @ngdoc method * @signature isCancelable() * @return {Boolean} * [en]true if the popover is cancelable.[/en] * [ja]ポップオーバーがキャンセル可能であればtrueとなります。[/ja] * @description * [en]Returns whether the popover is cancelable or not.[/en] * [ja]このポップオーバーがキャンセル可能かどうかを返します。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @param {Boolean} disabled * [en]If true the popover will be disabled.[/en] * [ja]ポップオーバーをdisabled状態にしたい場合にはtrueを指定します。[/ja] * @description * [en]Disable or enable the popover.[/en] * [ja]このポップオーバーをdisabled状態にするかどうかを設定します。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @return {Boolean} * [en]true if the popover is disabled.[/en] * [ja]ポップオーバーがdisabled状態であればtrueとなります。[/ja] * @description * [en]Returns whether the popover is disabled or enabled.[/en] * [ja]このポップオーバーがdisabled状態かどうかを返します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsPopover', ['$onsen', 'PopoverView', function($onsen, PopoverView) { return { restrict: 'E', replace: false, transclude: true, scope: true, templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/popover.tpl', compile: function(element, attrs, transclude) { return { pre: function(scope, element, attrs) { transclude(scope, function(clone) { angular.element(element[0].querySelector('.popover__content')).append(clone); }); var popover = new PopoverView(scope, element, attrs); $onsen.declareVarAttribute(attrs, popover); $onsen.registerEventHandlers(popover, 'preshow prehide postshow posthide destroy'); element.data('ons-popover', popover); scope.$on('$destroy', function() { popover._events = undefined; $onsen.removeModifierMethods(popover); element.data('ons-popover', undefined); element = null; }); scope.modifierTemplater = $onsen.generateModifierTemplater(attrs); $onsen.addModifierMethods(popover, 'popover--*', angular.element(element[0].querySelector('.popover'))); $onsen.addModifierMethods(popover, 'popover__content--*', angular.element(element[0].querySelector('.popover__content'))); if ($onsen.isAndroid()) { setImmediate(function() { popover.addModifier('android'); }); } scope.direction = 'up'; scope.arrowPosition = 'bottom'; }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id pull-hook * @name ons-pull-hook * @category control * @description * [en]Component that adds "pull-to-refresh" to an <ons-page> element.[/en] * [ja]ons-page要素以下でいわゆるpull to refreshを実装するためのコンポーネントです。[/ja] * @codepen WbJogM * @guide UsingPullHook * [en]How to use Pull Hook[/en] * [ja]プルフックを使う[/ja] * @example * <script> * ons.bootstrap() * * .controller('MyController', function($scope, $timeout) { * $scope.items = [3, 2 ,1]; * * $scope.load = function($done) { * $timeout(function() { * $scope.items.unshift($scope.items.length + 1); * $done(); * }, 1000); * }; * }); * </script> * * <ons-page ng-controller="MyController"> * <ons-pull-hook var="loaded" ng-action="load($done)"> * <span ng-switch="loader.getCurrentState()"> * <span ng-switch-when="initial">Pull down to refresh</span> * <span ng-switch-when="preaction">Release to refresh</span> * <span ng-switch-when="action">Loading data. Please wait...</span> * </span> * </ons-pull-hook> * <ons-list> * <ons-list-item ng-repeat="item in items"> * Item #{{ item }} * </ons-list-item> * </ons-list> * </ons-page> */ /** * @ngdoc event * @name changestate * @description * [en]Fired when the state is changed. The state can be either "initial", "preaction" or "action".[/en] * [ja]コンポーネントの状態が変わった場合に発火します。状態は、"initial", "preaction", "action"のいずれかです。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.pullHook * [en]Component object.[/en] * [ja]コンポーネントのオブジェクト。[/ja] * @param {String} event.state * [en]Current state.[/en] * [ja]現在の状態名を参照できます。[/ja] */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this component.[/en] * [ja]このコンポーネントを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]If this attribute is set the "pull-to-refresh" functionality is disabled.[/en] * [ja]この属性がある時、disabled状態になりアクションが実行されなくなります[/ja] */ /** * @ngdoc attribute * @name ng-action * @type {Expression} * @description * [en]Use to specify custom behavior when the page is pulled down. A <code>$done</code> function is available to tell the component that the action is completed.[/en] * [ja]pull downしたときの振る舞いを指定します。アクションが完了した時には<code>$done</code>関数を呼び出します。[/ja] */ /** * @ngdoc attribute * @name on-action * @type {Expression} * @description * [en]Same as <code>ng-action</code> but can be used without AngularJS. A function called <code>done</code> is available to call when action is complete.[/en] * [ja]<code>ng-action</code>と同じですが、AngularJS無しで利用する場合に利用できます。アクションが完了した時には<code>done</code>関数を呼び出します。[/ja] */ /** * @ngdoc attribute * @name height * @type {String} * @description * [en]Specify the height of the component. When pulled down further than this value it will switch to the "preaction" state. The default value is "64px".[/en] * [ja]コンポーネントの高さを指定します。この高さ以上にpull downすると"preaction"状態に移行します。デフォルトの値は"64px"です。[/ja] */ /** * @ngdoc attribute * @name threshold-height * @type {String} * @description * [en]Specify the threshold height. The component automatically switches to the "action" state when pulled further than this value. The default value is "96px". A negative value or a value less than the height will disable this property.[/en] * [ja]閾値となる高さを指定します。この値で指定した高さよりもpull downすると、このコンポーネントは自動的に"action"状態に移行します。[/ja] */ /** * @ngdoc attribute * @name ons-changestate * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "changestate" event is fired.[/en] * [ja]"changestate"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature setDisabled(disabled) * @param {Boolean} disabled * [en]If true the pull hook will be disabled.[/en] * [ja]trueを指定すると、プルフックがdisabled状態になります。[/ja] * @description * [en]Disable or enable the component.[/en] * [ja]disabled状態にするかどうかを設定できます。[/ja] */ /** * @ngdoc method * @signature isDisabled() * @return {Boolean} * [en]true if the pull hook is disabled.[/en] * [ja]プルフックがdisabled状態の場合、trueを返します。[/ja] * @description * [en]Returns whether the component is disabled or enabled.[/en] * [ja]dsiabled状態になっているかを得ることが出来ます。[/ja] */ /** * @ngdoc method * @signature setHeight(height) * @param {Number} height * [en]Desired height.[/en] * [ja]要素の高さを指定します。[/ja] * @description * [en]Specify the height.[/en] * [ja]高さを指定できます。[/ja] */ /** * @ngdoc method * @signature setThresholdHeight(thresholdHeight) * @param {Number} thresholdHeight * [en]Desired threshold height.[/en] * [ja]プルフックのアクションを起こす閾値となる高さを指定します。[/ja] * @description * [en]Specify the threshold height.[/en] * [ja]閾値となる高さを指定できます。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); /** * Pull hook directive. */ module.directive('onsPullHook', ['$onsen', 'PullHookView', function($onsen, PullHookView) { return { restrict: 'E', replace: false, scope: true, compile: function(element, attrs) { return { pre: function(scope, element, attrs) { var pullHook = new PullHookView(scope, element, attrs); $onsen.declareVarAttribute(attrs, pullHook); $onsen.registerEventHandlers(pullHook, 'changestate destroy'); element.data('ons-pull-hook', pullHook); scope.$on('$destroy', function() { pullHook._events = undefined; element.data('ons-pull-hook', undefined); scope = element = attrs = null; }); }, post: function(scope, element) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id row * @name ons-row * @category grid * @description * [en]Represents a row in the grid system. Use with ons-col to layout components.[/en] * [ja]グリッドシステムにて行を定義します。ons-colとともに使用し、コンポーネントの配置に使用します。[/ja] * @codepen GgujC {wide} * @guide Layouting * [en]Layouting guide[/en] * [ja]レイアウト調整[/ja] * @seealso ons-col * [en]ons-col component[/en] * [ja]ons-colコンポーネント[/ja] * @note * [en]For Android 4.3 and earlier, and iOS6 and earlier, when using mixed alignment with ons-row and ons-column, they may not be displayed correctly. You can use only one align.[/en] * [ja]Android 4.3以前、もしくはiOS 6以前のOSの場合、ons-rowとons-columnを組み合わせた場合に描画が崩れる場合があります。[/ja] * @example * <ons-row> * <ons-col width="50px"><ons-icon icon="fa-twitter"></ons-icon></ons-col> * <ons-col>Text</ons-col> * </ons-row> */ /** * @ngdoc attribute * @name align * @type {String} * @description * [en]Short hand attribute for aligning vertically. Valid values are top, bottom, and center.[/en] * [ja]縦に整列するために指定します。top、bottom、centerのいずれかを指定できます。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsRow', ['$onsen', '$timeout', function($onsen, $timeout) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: false, compile: function(element, attrs) { element.addClass('row ons-row-inner'); return function(scope, element, attrs) { attrs.$observe('align', function(align) { update(); }); update(); function update() { var align = ('' + attrs.align).trim(); if (align === 'top' || align === 'center' || align === 'bottom') { element.removeClass('row-bottom row-center row-top'); element.addClass('row-' + align); } } $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id scroller * @name ons-scroller * @category base * @description * [en]Makes the content inside this tag scrollable.[/en] * [ja]要素内をスクロール可能にします。[/ja] * @example * <ons-scroller style="height: 200px; width: 100%"> * ... * </ons-scroller> */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsScroller', ['$onsen', '$timeout', function($onsen, $timeout) { return { restrict: 'E', replace: false, transclude: true, scope: { onScrolled: '&', infinitScrollEnable: '=' }, compile: function(element, attrs) { var content = element.addClass('ons-scroller').children().remove(); return function(scope, element, attrs, controller, transclude) { if (attrs.ngController) { throw new Error('"ons-scroller" can\'t accept "ng-controller" directive.'); } var wrapper = angular.element('<div></div>'); wrapper.addClass('ons-scroller__content ons-scroller-inner'); element.append(wrapper); transclude(scope.$parent, function(cloned) { wrapper.append(cloned); wrapper = null; }); // inifinte scroll var scrollWrapper; scrollWrapper = element[0]; var offset = parseInt(attrs.threshold) || 10; if (scope.onScrolled) { scrollWrapper.addEventListener('scroll', function() { if (scope.infinitScrollEnable) { var scrollTopAndOffsetHeight = scrollWrapper.scrollTop + scrollWrapper.offsetHeight; var scrollHeightMinusOffset = scrollWrapper.scrollHeight - offset; if (scrollTopAndOffsetHeight >= scrollHeightMinusOffset) { scope.onScrolled(); } } }); } // IScroll for Android if (!Modernizr.csstransforms3d) { $timeout(function() { var iScroll = new IScroll(scrollWrapper, { momentum: true, bounce: true, hScrollbar: false, vScrollbar: false, preventDefault: false }); iScroll.on('scrollStart', function(e) { var scrolled = iScroll.y - offset; if (scrolled < (iScroll.maxScrollY + 40)) { // TODO: find a better way to know when content is upated so we can refresh iScroll.refresh(); } }); if (scope.onScrolled) { iScroll.on('scrollEnd', function(e) { var scrolled = iScroll.y - offset; if (scrolled < iScroll.maxScrollY) { // console.log('we are there!'); scope.onScrolled(); } }); } }, 500); } $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id sliding_menu * @name ons-sliding-menu * @category navigation * @description * [en]Component for sliding UI where one page is overlayed over another page. The above page can be slided aside to reveal the page behind.[/en] * [ja]スライディングメニューを表現するためのコンポーネントで、片方のページが別のページの上にオーバーレイで表示されます。above-pageで指定されたページは、横からスライドして表示します。[/ja] * @codepen IDvFJ * @seealso ons-page * [en]ons-page component[/en] * [ja]ons-pageコンポーネント[/ja] * @guide UsingSlidingMenu * [en]Using sliding menu[/en] * [ja]スライディングメニューを使う[/ja] * @guide EventHandling * [en]Using events[/en] * [ja]イベントの利用[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @example * <ons-sliding-menu var="app.menu" main-page="page.html" menu-page="menu.html" max-slide-distance="200px" type="reveal" side="left"> * </ons-sliding-menu> * * <ons-template id="page.html"> * <ons-page> * <p style="text-align: center"> * <ons-button ng-click="app.menu.toggleMenu()">Toggle</ons-button> * </p> * </ons-page> * </ons-template> * * <ons-template id="menu.html"> * <ons-page> * <!-- menu page's contents --> * </ons-page> * </ons-template> * */ /** * @ngdoc event * @name preopen * @description * [en]Fired just before the sliding menu is opened.[/en] * [ja]スライディングメニューが開く前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @ngdoc event * @name postopen * @description * [en]Fired just after the sliding menu is opened.[/en] * [ja]スライディングメニューが開き終わった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @ngdoc event * @name preclose * @description * [en]Fired just before the sliding menu is closed.[/en] * [ja]スライディングメニューが閉じる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @ngdoc event * @name postclose * @description * [en]Fired just after the sliding menu is closed.[/en] * [ja]スライディングメニューが閉じ終わった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.slidingMenu * [en]Sliding menu view object.[/en] * [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja] */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this sliding menu.[/en] * [ja]このスライディングメニューを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name menu-page * @type {String} * @description * [en]The url of the menu page.[/en] * [ja]左に位置するメニューページのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name main-page * @type {String} * @description * [en]The url of the main page.[/en] * [ja]右に位置するメインページのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name swipeable * @type {Boolean} * @description * [en]Whether to enable swipe interaction.[/en] * [ja]スワイプ操作を有効にする場合に指定します。[/ja] */ /** * @ngdoc attribute * @name swipe-target-width * @type {String} * @description * [en]The width of swipeable area calculated from the left (in pixels). Use this to enable swipe only when the finger touch on the screen edge.[/en] * [ja]スワイプの判定領域をピクセル単位で指定します。画面の端から指定した距離に達するとページが表示されます。[/ja] */ /** * @ngdoc attribute * @name max-slide-distance * @type {String} * @description * [en]How far the menu page will slide open. Can specify both in px and %. eg. 90%, 200px[/en] * [ja]menu-pageで指定されたページの表示幅を指定します。ピクセルもしくは%の両方で指定できます(例: 90%, 200px)[/ja] */ /** * @ngdoc attribute * @name direction * @type {String} * @description * [en]Specify which side of the screen the menu page is located on. Possible values are "left" and "right".[/en] * [ja]menu-pageで指定されたページが画面のどちら側から表示されるかを指定します。leftもしくはrightのいずれかを指定できます。[/ja] */ /** * @ngdoc attribute * @name type * @type {String} * @description * [en]Sliding menu animator. Possible values are reveal (default), push and overlay.[/en] * [ja]スライディングメニューのアニメーションです。"reveal"(デフォルト)、"push"、"overlay"のいずれかを指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-preopen * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preopen" event is fired.[/en] * [ja]"preopen"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-preclose * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "preclose" event is fired.[/en] * [ja]"preclose"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postopen * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postopen" event is fired.[/en] * [ja]"postopen"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postclose * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postclose" event is fired.[/en] * [ja]"postclose"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature setMainPage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Boolean} [options.closeMenu] * [en]If true the menu will be closed.[/en] * [ja]trueを指定すると、開いているメニューを閉じます。[/ja] * @param {Function} [options.callback] * [en]Function that is executed after the page has been set.[/en] * [ja]ページが読み込まれた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the main contents pane.[/en] * [ja]中央部分に表示されるページをpageUrlに指定します。[/ja] */ /** * @ngdoc method * @signature setMenuPage(pageUrl, [options]) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Boolean} [options.closeMenu] * [en]If true the menu will be closed after the menu page has been set.[/en] * [ja]trueを指定すると、開いているメニューを閉じます。[/ja] * @param {Function} [options.callback] * [en]This function will be executed after the menu page has been set.[/en] * [ja]メニューページが読み込まれた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the side menu pane.[/en] * [ja]メニュー部分に表示されるページをpageUrlに指定します。[/ja] */ /** * @ngdoc method * @signature openMenu([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been opened.[/en] * [ja]メニューが開いた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Slide the above layer to reveal the layer behind.[/en] * [ja]メニューページを表示します。[/ja] */ /** * @ngdoc method * @signature closeMenu([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been closed.[/en] * [ja]メニューが閉じられた後に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en]Slide the above layer to hide the layer behind.[/en] * [ja]メニューページを非表示にします。[/ja] */ /** * @ngdoc method * @signature toggleMenu([options]) * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Function} [options.callback] * [en]This function will be called after the menu has been opened or closed.[/en] * [ja]メニューが開き終わった後か、閉じ終わった後に呼び出される関数オブジェクトです。[/ja] * @description * [en]Slide the above layer to reveal the layer behind if it is currently hidden, otherwise, hide the layer behind.[/en] * [ja]現在の状況に合わせて、メニューページを表示もしくは非表示にします。[/ja] */ /** * @ngdoc method * @signature isMenuOpened() * @return {Boolean} * [en]true if the menu is currently open.[/en] * [ja]メニューが開いていればtrueとなります。[/ja] * @description * [en]Returns true if the menu page is open, otherwise false.[/en] * [ja]メニューページが開いている場合はtrue、そうでない場合はfalseを返します。[/ja] */ /** * @ngdoc method * @signature getDeviceBackButtonHandler() * @return {Object} * [en]Device back button handler.[/en] * [ja]デバイスのバックボタンハンドラを返します。[/ja] * @description * [en]Retrieve the back-button handler.[/en] * [ja]ons-sliding-menuに紐付いているバックボタンハンドラを取得します。[/ja] */ /** * @ngdoc method * @signature setSwipeable(swipeable) * @param {Boolean} swipeable * [en]If true the menu will be swipeable.[/en] * [ja]スワイプで開閉できるようにする場合にはtrueを指定します。[/ja] * @description * [en]Specify if the menu should be swipeable or not.[/en] * [ja]スワイプで開閉するかどうかを設定する。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsSlidingMenu', ['$compile', 'SlidingMenuView', '$onsen', function($compile, SlidingMenuView, $onsen) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclude. transclude: false, scope: true, compile: function(element, attrs) { var main = element[0].querySelector('.main'), menu = element[0].querySelector('.menu'); if (main) { var mainHtml = angular.element(main).remove().html().trim(); } if (menu) { var menuHtml = angular.element(menu).remove().html().trim(); } return function(scope, element, attrs) { if (attrs.ngController) { throw new Error('This element can\'t accept ng-controller directive.'); } element.append(angular.element('<div></div>').addClass('onsen-sliding-menu__menu ons-sliding-menu-inner')); element.append(angular.element('<div></div>').addClass('onsen-sliding-menu__main ons-sliding-menu-inner')); var slidingMenu = new SlidingMenuView(scope, element, attrs); $onsen.registerEventHandlers(slidingMenu, 'preopen preclose postopen postclose destroy'); if (mainHtml && !attrs.mainPage) { slidingMenu._appendMainPage(null, mainHtml); } if (menuHtml && !attrs.menuPage) { slidingMenu._appendMenuPage(menuHtml); } $onsen.declareVarAttribute(attrs, slidingMenu); element.data('ons-sliding-menu', slidingMenu); element.data('_scope', scope); scope.$on('$destroy', function() { element.data('_scope', undefined); slidingMenu._events = undefined; element.data('ons-sliding-menu', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id split-view * @name ons-split-view * @category control * @description * [en]Divides the screen into a left and right section.[/en] * [ja]画面を左右に分割するコンポーネントです。[/ja] * @codepen nKqfv {wide} * @guide Usingonssplitviewcomponent * [en]Using ons-split-view.[/en] * [ja]ons-split-viewコンポーネントを使う[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @example * <ons-split-view * secondary-page="secondary.html" * main-page="main.html" * main-page-width="70%" * collapse="portrait"> * </ons-split-view> */ /** * @ngdoc event * @name update * @description * [en]Fired when the split view is updated.[/en] * [ja]split viewの状態が更新された際に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Boolean} event.shouldCollapse * [en]True if the view should collapse.[/en] * [ja]collapse状態の場合にtrueになります。[/ja] * @param {String} event.currentMode * [en]Current mode.[/en] * [ja]現在のモード名を返します。"collapse"か"split"かのいずれかです。[/ja] * @param {Function} event.split * [en]Call to force split.[/en] * [ja]この関数を呼び出すと強制的にsplitモードにします。[/ja] * @param {Function} event.collapse * [en]Call to force collapse.[/en] * [ja]この関数を呼び出すと強制的にcollapseモードにします。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewの幅を返します。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"かもしくは"landscape"です。 [/ja] */ /** * @ngdoc event * @name presplit * @description * [en]Fired just before the view is split.[/en] * [ja]split状態にる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @ngdoc event * @name postsplit * @description * [en]Fired just after the view is split.[/en] * [ja]split状態になった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @ngdoc event * @name precollapse * @description * [en]Fired just before the view is collapsed.[/en] * [ja]collapse状態になる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @ngdoc event * @name postcollapse * @description * [en]Fired just after the view is collapsed.[/en] * [ja]collapse状態になった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.splitView * [en]Split view object.[/en] * [ja]イベントが発火したSplitViewオブジェクトです。[/ja] * @param {Number} event.width * [en]Current width.[/en] * [ja]現在のSplitViewnの幅です。[/ja] * @param {String} event.orientation * [en]Current orientation.[/en] * [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja] */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this split view.[/en] * [ja]このスプリットビューコンポーネントを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name main-page * @type {String} * @description * [en]The url of the page on the right.[/en] * [ja]右側に表示するページのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name main-page-width * @type {Number} * @description * [en]Main page width percentage. The secondary page width will be the remaining percentage.[/en] * [ja]右側のページの幅をパーセント単位で指定します。[/ja] */ /** * @ngdoc attribute * @name secondary-page * @type {String} * @description * [en]The url of the page on the left.[/en] * [ja]左側に表示するページのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name collapse * @type {String} * @description * [en] * Specify the collapse behavior. Valid values are portrait, landscape, width #px or a media query. * "portrait" or "landscape" means the view will collapse when device is in landscape or portrait orientation. * "width #px" means the view will collapse when the window width is smaller than the specified #px. * If the value is a media query, the view will collapse when the media query is true. * [/en] * [ja] * 左側のページを非表示にする条件を指定します。portrait, landscape、width #pxもしくはメディアクエリの指定が可能です。 * portraitもしくはlandscapeを指定すると、デバイスの画面が縦向きもしくは横向きになった時に適用されます。 * width #pxを指定すると、画面が指定した横幅よりも短い場合に適用されます。 * メディアクエリを指定すると、指定したクエリに適合している場合に適用されます。 * [/ja] */ /** * @ngdoc attribute * @name ons-update * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "update" event is fired.[/en] * [ja]"update"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-presplit * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "presplit" event is fired.[/en] * [ja]"presplit"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-precollapse * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "precollapse" event is fired.[/en] * [ja]"precollapse"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postsplit * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postsplit" event is fired.[/en] * [ja]"postsplit"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postcollapse * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postcollapse" event is fired.[/en] * [ja]"postcollapse"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature setMainPage(pageUrl) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <ons-template>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the right section[/en] * [ja]指定したURLをメインページを読み込みます。[/ja] */ /** * @ngdoc method * @signature setSecondaryPage(pageUrl) * @param {String} pageUrl * [en]Page URL. Can be either an HTML document or an <ons-template>.[/en] * [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja] * @description * [en]Show the page specified in pageUrl in the left section[/en] * [ja]指定したURLを左のページの読み込みます。[/ja] */ /** * @ngdoc method * @signature update() * @description * [en]Trigger an 'update' event and try to determine if the split behaviour should be changed.[/en] * [ja]splitモードを変えるべきかどうかを判断するための'update'イベントを発火します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsSplitView', ['$compile', 'SplitView', '$onsen', function($compile, SplitView, $onsen) { return { restrict: 'E', replace: false, transclude: false, scope: true, compile: function(element, attrs) { var mainPage = element[0].querySelector('.main-page'), secondaryPage = element[0].querySelector('.secondary-page'); if (mainPage) { var mainHtml = angular.element(mainPage).remove().html().trim(); } if (secondaryPage) { var secondaryHtml = angular.element(secondaryPage).remove().html().trim(); } return function(scope, element, attrs) { if (attrs.ngController) { throw new Error('This element can\'t accept ng-controller directive.'); } element.append(angular.element('<div></div>').addClass('onsen-split-view__secondary full-screen ons-split-view-inner')); element.append(angular.element('<div></div>').addClass('onsen-split-view__main full-screen ons-split-view-inner')); var splitView = new SplitView(scope, element, attrs); if (mainHtml && !attrs.mainPage) { splitView._appendMainPage(mainHtml); } if (secondaryHtml && !attrs.secondaryPage) { splitView._appendSecondPage(secondaryHtml); } $onsen.declareVarAttribute(attrs, splitView); $onsen.registerEventHandlers(splitView, 'update presplit precollapse postsplit postcollapse destroy'); element.data('ons-split-view', splitView); element.data('_scope', scope); scope.$on('$destroy', function() { element.data('_scope', undefined); splitView._events = undefined; element.data('ons-split-view', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id switch * @name ons-switch * @category form * @description * [en]Switch component.[/en] * [ja]スイッチを表示するコンポーネントです。[/ja] * @guide UsingFormComponents * [en]Using form components[/en] * [ja]フォームを使う[/ja] * @guide EventHandling * [en]Event handling descriptions[/en] * [ja]イベント処理の使い方[/ja] * @seealso ons-button * [en]ons-button component[/en] * [ja]ons-buttonコンポーネント[/ja] * @example * <ons-switch checked></ons-switch> */ /** * @ngdoc event * @name change * @description * [en]Fired when the value is changed.[/en] * [ja]ON/OFFが変わった時に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.switch * [en]Switch object.[/en] * [ja]イベントが発火したSwitchオブジェクトを返します。[/ja] * @param {Boolean} event.value * [en]Current value.[/en] * [ja]現在の値を返します。[/ja] * @param {Boolean} event.isInteractive * [en]True if the change was triggered by the user clicking on the switch.[/en] * [ja]タップやクリックなどのユーザの操作によって変わった場合にはtrueを返します。[/ja] */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this switch.[/en] * [ja]JavaScriptから参照するための変数名を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the switch.[/en] * [ja]スイッチの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]Whether the switch should be disabled.[/en] * [ja]スイッチを無効の状態にする場合に指定します。[/ja] */ /** * @ngdoc attribute * @name checked * @description * [en]Whether the switch is checked.[/en] * [ja]スイッチがONの状態にするときに指定します。[/ja] */ /** * @ngdoc method * @signature isChecked() * @return {Boolean} * [en]true if the switch is on.[/en] * [ja]ONになっている場合にはtrueになります。[/ja] * @description * [en]Returns true if the switch is ON.[/en] * [ja]スイッチがONの場合にtrueを返します。[/ja] */ /** * @ngdoc method * @signature setChecked(checked) * @param {Boolean} checked * [en]If true the switch will be set to on.[/en] * [ja]ONにしたい場合にはtrueを指定します。[/ja] * @description * [en]Set the value of the switch. isChecked can be either true or false.[/en] * [ja]スイッチの値を指定します。isCheckedにはtrueもしくはfalseを指定します。[/ja] */ /** * @ngdoc method * @signature getCheckboxElement() * @return {HTMLElement} * [en]The underlying checkbox element.[/en] * [ja]コンポーネント内部のcheckbox要素になります。[/ja] * @description * [en]Get inner input[type=checkbox] element.[/en] * [ja]スイッチが内包する、input[type=checkbox]の要素を取得します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsSwitch', ['$onsen', '$parse', 'SwitchView', function($onsen, $parse, SwitchView) { return { restrict: 'E', replace: false, transclude: false, scope: true, templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/switch.tpl', compile: function(element) { return function(scope, element, attrs) { if (attrs.ngController) { throw new Error('This element can\'t accept ng-controller directive.'); } var switchView = new SwitchView(element, scope, attrs); var checkbox = angular.element(element[0].querySelector('input[type=checkbox]')); scope.modifierTemplater = $onsen.generateModifierTemplater(attrs); var label = element.children(), input = angular.element(label.children()[0]), toggle = angular.element(label.children()[1]); $onsen.addModifierMethods(switchView, 'switch--*', label); $onsen.addModifierMethods(switchView, 'switch--*__input', input); $onsen.addModifierMethods(switchView, 'switch--*__toggle', toggle); attrs.$observe('checked', function(checked) { scope.model = !!element.attr('checked'); }); attrs.$observe('name', function(name) { if (!!element.attr('name')) { checkbox.attr('name', name); } }); if (attrs.ngModel) { var set = $parse(attrs.ngModel).assign; scope.$parent.$watch(attrs.ngModel, function(value) { scope.model = value; }); scope.$watch('model', function(to, from) { set(scope.$parent, to); if (to !== from) { scope.$eval(attrs.ngChange); } }); } $onsen.declareVarAttribute(attrs, switchView); element.data('ons-switch', switchView); $onsen.cleaner.onDestroy(scope, function() { switchView._events = undefined; $onsen.removeModifierMethods(switchView); element.data('ons-switch', undefined); $onsen.clearComponent({ element : element, scope : scope, attrs : attrs }); checkbox = element = attrs = scope = null; }); $onsen.fireComponentEvent(element[0], 'init'); }; } }; }]); })(); /** * @ngdoc directive * @id tabbar_item * @name ons-tab * @category navigation * @description * [en]Represents a tab inside tabbar. Each ons-tab represents a page.[/en] * [ja] * タブバーに配置される各アイテムのコンポーネントです。それぞれのons-tabはページを表します。 * ons-tab要素の中には、タブに表示されるコンテンツを直接記述することが出来ます。 * [/ja] * @codepen pGuDL * @guide UsingTabBar * [en]Using tab bar[/en] * [ja]タブバーを使う[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @seealso ons-tabbar * [en]ons-tabbar component[/en] * [ja]ons-tabbarコンポーネント[/ja] * @seealso ons-page * [en]ons-page component[/en] * [ja]ons-pageコンポーネント[/ja] * @seealso ons-icon * [en]ons-icon component[/en] * [ja]ons-iconコンポーネント[/ja] * @example * <ons-tabbar> * <ons-tab page="home.html" active="true"> * <ons-icon icon="ion-home"></ons-icon> * <span style="font-size: 14px">Home</span> * </ons-tab> * <ons-tab page="fav.html" active="true"> * <ons-icon icon="ion-star"></ons-icon> * <span style="font-size: 14px">Favorites</span> * </ons-tab> * <ons-tab page="settings.html" active="true"> * <ons-icon icon="ion-gear-a"></ons-icon> * <span style="font-size: 14px">Settings</span> * </ons-tab> * </ons-tabbar> * * <ons-template id="home.html"> * ... * </ons-template> * * <ons-template id="fav.html"> * ... * </ons-template> * * <ons-template id="settings.html"> * ... * </ons-template> */ /** * @ngdoc attribute * @name page * @type {String} * @description * [en]The page that this <code>&lt;ons-tab&gt;</code> points to.[/en] * [ja]<code>&lt;ons-tab&gt;</code>が参照するページへのURLを指定します。[/ja] */ /** * @ngdoc attribute * @name icon * @type {String} * @description * [en] * The icon name for the tab. Can specify the same icon name as <code>&lt;ons-icon&gt;</code>. * If you need to use your own icon, create a css class with background-image or any css properties and specify the name of your css class here. * [/en] * [ja] * アイコン名を指定します。<code>&lt;ons-icon&gt;</code>と同じアイコン名を指定できます。 * 個別にアイコンをカスタマイズする場合は、background-imageなどのCSSスタイルを用いて指定できます。 * [/ja] */ /** * @ngdoc attribute * @name active-icon * @type {String} * @description * [en]The name of the icon when the tab is active.[/en] * [ja]アクティブの際のアイコン名を指定します。[/ja] */ /** * @ngdoc attribute * @name label * @type {String} * @description * [en]The label of the tab item.[/en] * [ja]アイコン下に表示されるラベルを指定します。[/ja] */ /** * @ngdoc attribute * @name active * @type {Boolean} * @default false * @description * [en]Set whether this item should be active or not. Valid values are true and false.[/en] * [ja]このタブアイテムをアクティブ状態にするかどうかを指定します。trueもしくはfalseを指定できます。[/ja] */ /** * @ngdoc attribute * @name no-reload * @description * [en]Set if the page shouldn't be reloaded when clicking on the same tab twice.[/en] * [ja]すでにアクティブになったタブを再びクリックするとページの再読み込みは発生しません。[/ja] */ /** * @ngdoc attribute * @name persistent * @description * [en] * Set to make the tab content persistent. * If this attribute it set the DOM will not be destroyed when navigating to another tab. * [/en] * [ja] * このタブで読み込んだページを永続化します。 * この属性があるとき、別のタブのページに切り替えても、 * 読み込んだページのDOM要素は破棄されずに単に非表示になります。 * [/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsTab', tab); module.directive('onsTabbarItem', tab); // for BC var defaultInnerTemplate = '<div ng-if="icon != undefined" class="tab-bar__icon">' + '<ons-icon icon="{{tabIcon}}" style="font-size: 28px; line-height: 34px; vertical-align: top;"></ons-icon>' + '</div>' + '<div ng-if="label" class="tab-bar__label">{{label}}</div>'; function tab($onsen, $compile) { return { restrict: 'E', transclude: true, scope: { page: '@', active: '@', icon: '@', activeIcon: '@', label: '@', noReload: '@', persistent: '@' }, templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/tab.tpl', compile: function(element, attrs) { element.addClass('tab-bar__item'); return function(scope, element, attrs, controller, transclude) { var tabbarView = element.inheritedData('ons-tabbar'); if (!tabbarView) { throw new Error('This ons-tab element is must be child of ons-tabbar element.'); } element.addClass(tabbarView._scope.modifierTemplater('tab-bar--*__item')); element.addClass(tabbarView._scope.modifierTemplater('tab-bar__item--*')); transclude(scope.$parent, function(cloned) { var wrapper = angular.element(element[0].querySelector('.tab-bar-inner')); if (attrs.icon || attrs.label || !cloned[0]) { var innerElement = angular.element('<div>' + defaultInnerTemplate + '</div>').children(); wrapper.append(innerElement); $compile(innerElement)(scope); } else { wrapper.append(cloned); } }); var radioButton = element[0].querySelector('input'); scope.tabbarModifierTemplater = tabbarView._scope.modifierTemplater; scope.modifierTemplater = $onsen.generateModifierTemplater(attrs); scope.tabbarId = tabbarView._tabbarId; scope.tabIcon = scope.icon; tabbarView.addTabItem(scope); // Make this tab active. scope.setActive = function() { element.addClass('active'); radioButton.checked = true; if (scope.activeIcon) { scope.tabIcon = scope.activeIcon; } angular.element(element[0].querySelectorAll('[ons-tab-inactive]')).css('display', 'none'); angular.element(element[0].querySelectorAll('[ons-tab-active]')).css('display', 'inherit'); }; // Make this tab inactive. scope.setInactive = function() { element.removeClass('active'); radioButton.checked = false; scope.tabIcon = scope.icon; angular.element(element[0].querySelectorAll('[ons-tab-inactive]')).css('display', 'inherit'); angular.element(element[0].querySelectorAll('[ons-tab-active]')).css('display', 'none'); }; scope.isPersistent = function() { return typeof scope.persistent != 'undefined'; }; /** * @return {Boolean} */ scope.isActive = function() { return element.hasClass('active'); }; scope.tryToChange = function() { tabbarView.setActiveTab(tabbarView._tabItems.indexOf(scope)); }; if (scope.active) { tabbarView.setActiveTab(tabbarView._tabItems.indexOf(scope)); } $onsen.fireComponentEvent(element[0], 'init'); }; } }; } tab.$inject = ['$onsen', '$compile']; })(); /** * @ngdoc directive * @id tabbar * @name ons-tabbar * @category navigation * @description * [en]A component to display a tab bar on the bottom of a page. Used with ons-tab to manage pages using tabs.[/en] * [ja]タブバーをページ下部に表示するためのコンポーネントです。ons-tabと組み合わせて使うことで、ページを管理できます。[/ja] * @codepen pGuDL * @guide UsingTabBar * [en]Using tab bar[/en] * [ja]タブバーを使う[/ja] * @guide EventHandling * [en]Event handling descriptions[/en] * [ja]イベント処理の使い方[/ja] * @guide CallingComponentAPIsfromJavaScript * [en]Using navigator from JavaScript[/en] * [ja]JavaScriptからコンポーネントを呼び出す[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @seealso ons-tab * [en]ons-tab component[/en] * [ja]ons-tabコンポーネント[/ja] * @seealso ons-page * [en]ons-page component[/en] * [ja]ons-pageコンポーネント[/ja] * @example * <ons-tabbar> * <ons-tab page="home.html" active="true"> * <ons-icon icon="ion-home"></ons-icon> * <span style="font-size: 14px">Home</span> * </ons-tab> * <ons-tab page="fav.html" active="true"> * <ons-icon icon="ion-star"></ons-icon> * <span style="font-size: 14px">Favorites</span> * </ons-tab> * <ons-tab page="settings.html" active="true"> * <ons-icon icon="ion-gear-a"></ons-icon> * <span style="font-size: 14px">Settings</span> * </ons-tab> * </ons-tabbar> * * <ons-template id="home.html"> * ... * </ons-template> * * <ons-template id="fav.html"> * ... * </ons-template> * * <ons-template id="settings.html"> * ... * </ons-template> */ /** * @ngdoc event * @name prechange * @description * [en]Fires just before the tab is changed.[/en] * [ja]アクティブなタブが変わる前に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Number} event.index * [en]Current index.[/en] * [ja]現在アクティブになっているons-tabのインデックスを返します。[/ja] * @param {Object} event.tabItem * [en]Tab item object.[/en] * [ja]tabItemオブジェクト。[/ja] * @param {Function} event.cancel * [en]Call this function to cancel the change event.[/en] * [ja]この関数を呼び出すと、アクティブなタブの変更がキャンセルされます。[/ja] */ /** * @ngdoc event * @name postchange * @description * [en]Fires just after the tab is changed.[/en] * [ja]アクティブなタブが変わった後に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Number} event.index * [en]Current index.[/en] * [ja]現在アクティブになっているons-tabのインデックスを返します。[/ja] * @param {Object} event.tabItem * [en]Tab item object.[/en] * [ja]tabItemオブジェクト。[/ja] */ /** * @ngdoc event * @name reactive * @description * [en]Fires if the already open tab is tapped again.[/en] * [ja]すでにアクティブになっているタブがもう一度タップやクリックされた場合に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Number} event.index * [en]Current index.[/en] * [ja]現在アクティブになっているons-tabのインデックスを返します。[/ja] * @param {Object} event.tabItem * [en]Tab item object.[/en] * [ja]tabItemオブジェクト。[/ja] */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this tab bar.[/en] * [ja]このタブバーを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name hide-tabs * @type {Boolean} * @default false * @description * [en]Whether to hide the tabs. Valid values are true/false.[/en] * [ja]タブを非表示にする場合に指定します。trueもしくはfalseを指定できます。[/ja] */ /** * @ngdoc attribute * @name animation * @type {String} * @default none * @description * [en]Animation name. Preset values are "none" and "fade". Default is "none".[/en] * [ja]ページ読み込み時のアニメーションを指定します。"none"もしくは"fade"を選択できます。デフォルトは"none"です。[/ja] */ /** * @ngdoc attribute * @name position * @type {String} * @default bottom * @description * [en]Tabbar's position. Preset values are "bottom" and "top". Default is "bottom".[/en] * [ja]タブバーの位置を指定します。"bottom"もしくは"top"を選択できます。デフォルトは"bottom"です。[/ja] */ /** * @ngdoc attribute * @name ons-reactive * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "reactive" event is fired.[/en] * [ja]"reactive"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-prechange * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "prechange" event is fired.[/en] * [ja]"prechange"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-postchange * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "postchange" event is fired.[/en] * [ja]"postchange"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc attribute * @name ons-destroy * @type {Expression} * @description * [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en] * [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja] */ /** * @ngdoc method * @signature setActiveTab(index, [options]) * @param {Number} index * [en]Tab index.[/en] * [ja]タブのインデックスを指定します。[/ja] * @param {Object} [options] * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクト。[/ja] * @param {Boolean} [options.keepPage] * [en]If true the page will not be changed.[/en] * [ja]タブバーが現在表示しているpageを変えない場合にはtrueを指定します。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "fade" and "none".[/en] * [ja]アニメーション名を指定します。"fade", "none"のいずれかを指定できます。[/ja] * @return {Boolean} * [en]true if the change was successful.[/en] * [ja]変更が成功した場合にtrueを返します。[/ja] * @description * [en]Show specified tab page. Animations and other options can be specified by the second parameter.[/en] * [ja]指定したインデックスのタブを表示します。アニメーションなどのオプションを指定できます。[/ja] */ /** * @ngdoc method * @signature getActiveTabIndex() * @return {Number} * [en]The index of the currently active tab.[/en] * [ja]現在アクティブになっているタブのインデックスを返します。[/ja] * @description * [en]Returns tab index on current active tab. If active tab is not found, returns -1.[/en] * [ja]現在アクティブになっているタブのインデックスを返します。現在アクティブなタブがない場合には-1を返します。[/ja] */ /** * @ngdoc method * @signature loadPage(url) * @param {String} url * [en]Page URL. Can be either an HTML document or an <code>&lt;ons-template&gt;</code>.[/en] * [ja]pageのURLか、もしくは<code>&lt;ons-template&gt;</code>で宣言したid属性の値を利用できます。[/ja] * @description * [en]Displays a new page without changing the active index.[/en] * [ja]現在のアクティブなインデックスを変更せずに、新しいページを表示します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); module.directive('onsTabbar', ['$onsen', '$compile', 'TabbarView', function($onsen, $compile, TabbarView) { return { restrict: 'E', replace: false, transclude: true, scope: true, templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/tab_bar.tpl', link: function(scope, element, attrs, controller, transclude) { scope.modifierTemplater = $onsen.generateModifierTemplater(attrs); scope.selectedTabItem = {source: ''}; attrs.$observe('hideTabs', function(hide) { var visible = hide !== 'true'; tabbarView.setTabbarVisibility(visible); }); var tabbarView = new TabbarView(scope, element, attrs); $onsen.addModifierMethods(tabbarView, 'tab-bar--*', angular.element(element.children()[1])); $onsen.registerEventHandlers(tabbarView, 'reactive prechange postchange destroy'); scope.tabbarId = tabbarView._tabbarId; element.data('ons-tabbar', tabbarView); $onsen.declareVarAttribute(attrs, tabbarView); transclude(scope, function(cloned) { angular.element(element[0].querySelector('.ons-tabbar-inner')).append(cloned); }); scope.$on('$destroy', function() { tabbarView._events = undefined; $onsen.removeModifierMethods(tabbarView); element.data('ons-tabbar', undefined); }); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id template * @name ons-template * @category util * @description * [en]Define a separate HTML fragment and use as a template.[/en] * [ja]テンプレートとして使用するためのHTMLフラグメントを定義します。この要素でHTMLを宣言すると、id属性に指定した名前をpageのURLとしてons-navigatorなどのコンポーネントから参照できます。[/ja] * @guide DefiningMultiplePagesinSingleHTML * [en]Defining multiple pages in single html[/en] * [ja]複数のページを1つのHTMLに記述する[/ja] * @example * <ons-template id="foobar.html"> * ... * </ons-template> */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsTemplate', ['$onsen', '$templateCache', function($onsen, $templateCache) { return { restrict: 'E', transclude: false, priority: 1000, terminal: true, compile: function(element) { $templateCache.put(element.attr('id'), element.remove().html()); $onsen.fireComponentEvent(element[0], 'init'); } }; }]); })(); /** * @ngdoc directive * @id toolbar * @name ons-toolbar * @category toolbar * @modifier transparent * [en]Transparent toolbar[/en] * [ja]透明な背景を持つツールバーを表示します。[/ja] * @modifier android * [en]Android style toolbar. Title is left-aligned.[/en] * [ja]Androidライクなツールバーを表示します。タイトルが左に寄ります。[/ja] * @description * [en]Toolbar component that can be used with navigation. Left, center and right container can be specified by class names.[/en] * [ja]ナビゲーションで使用するツールバー用コンポーネントです。クラス名により、左、中央、右のコンテナを指定できます。[/ja] * @codepen aHmGL * @guide Addingatoolbar [en]Adding a toolbar[/en][ja]ツールバーの追加[/ja] * @seealso ons-bottom-toolbar * [en]ons-bottom-toolbar component[/en] * [ja]ons-bottom-toolbarコンポーネント[/ja] * @seealso ons-back-button * [en]ons-back-button component[/en] * [ja]ons-back-buttonコンポーネント[/ja] * @seealso ons-toolbar-button * [en]ons-toolbar-button component[/en] * [ja]ons-toolbar-buttonコンポーネント[/ja] * @example * <ons-page> * <ons-toolbar> * <div class="left"><ons-back-button>Back</ons-back-button></div> * <div class="center">Title</div> * <div class="right">Label</div> * </ons-toolbar> * </ons-page> */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this toolbar.[/en] * [ja]このツールバーを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name inline * @description * [en]Display the toolbar as an inline element.[/en] * [ja]ツールバーをインラインに置きます。スクロール領域内にそのまま表示されます。[/ja] */ /** * @ngdoc attribute * @name modifier * @description * [en]The appearance of the toolbar.[/en] * [ja]ツールバーの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name fixed-style * @description * [en] * By default the center element will be left-aligned on Android and center-aligned on iOS. * Use this attribute to override this behavior so it's always displayed in the center. * [/en] * [ja] * このコンポーネントは、Androidではタイトルを左寄せ、iOSでは中央配置します。 * この属性を使用すると、要素はAndroidとiOSともに中央配置となります。 * [/ja] */ (function() { 'use strict'; var module = angular.module('onsen'); function ensureLeftContainer(element, modifierTemplater) { var container = element[0].querySelector('.left'); if (!container) { container = document.createElement('div'); container.setAttribute('class', 'left'); container.innerHTML = '&nbsp;'; } if (container.innerHTML.trim() === '') { container.innerHTML = '&nbsp;'; } angular.element(container) .addClass('navigation-bar__left') .addClass(modifierTemplater('navigation-bar--*__left')); return container; } function ensureCenterContainer(element, modifierTemplater) { var container = element[0].querySelector('.center'); if (!container) { container = document.createElement('div'); container.setAttribute('class', 'center'); } if (container.innerHTML.trim() === '') { container.innerHTML = '&nbsp;'; } angular.element(container) .addClass('navigation-bar__title navigation-bar__center') .addClass(modifierTemplater('navigation-bar--*__center')); return container; } function ensureRightContainer(element, modifierTemplater) { var container = element[0].querySelector('.right'); if (!container) { container = document.createElement('div'); container.setAttribute('class', 'right'); container.innerHTML = '&nbsp;'; } if (container.innerHTML.trim() === '') { container.innerHTML = '&nbsp;'; } angular.element(container) .addClass('navigation-bar__right') .addClass(modifierTemplater('navigation-bar--*__right')); return container; } /** * @param {jqLite} element * @return {Boolean} */ function hasCenterClassElementOnly(element) { var hasCenter = false; var hasOther = false; var child, children = element.contents(); for (var i = 0; i < children.length; i++) { child = angular.element(children[i]); if (child.hasClass('center')) { hasCenter = true; continue; } if (child.hasClass('left') || child.hasClass('right')) { hasOther = true; continue; } } return hasCenter && !hasOther; } function ensureToolbarItemElements(element, modifierTemplater) { var center; if (hasCenterClassElementOnly(element)) { center = ensureCenterContainer(element, modifierTemplater); element.contents().remove(); element.append(center); } else { center = ensureCenterContainer(element, modifierTemplater); var left = ensureLeftContainer(element, modifierTemplater); var right = ensureRightContainer(element, modifierTemplater); element.contents().remove(); element.append(angular.element([left, center, right])); } } /** * Toolbar directive. */ module.directive('onsToolbar', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', replace: false, // NOTE: This element must coexists with ng-controller. // Do not use isolated scope and template's ng-transclde. scope: false, transclude: false, compile: function(element, attrs) { var shouldAppendAndroidModifier = ons.platform.isAndroid() && !element[0].hasAttribute('fixed-style'); var modifierTemplater = $onsen.generateModifierTemplater(attrs, shouldAppendAndroidModifier ? ['android'] : []), inline = typeof attrs.inline !== 'undefined'; element.addClass('navigation-bar'); element.addClass(modifierTemplater('navigation-bar--*')); if (!inline) { element.css({ 'position': 'absolute', 'z-index': '10000', 'left': '0px', 'right': '0px', 'top': '0px' }); } ensureToolbarItemElements(element, modifierTemplater); return { pre: function(scope, element, attrs) { var toolbar = new GenericView(scope, element, attrs); $onsen.declareVarAttribute(attrs, toolbar); scope.$on('$destroy', function() { toolbar._events = undefined; $onsen.removeModifierMethods(toolbar); element.data('ons-toolbar', undefined); element = null; }); $onsen.addModifierMethods(toolbar, 'navigation-bar--*', element); angular.forEach(['left', 'center', 'right'], function(position) { var el = element[0].querySelector('.navigation-bar__' + position); if (el) { $onsen.addModifierMethods(toolbar, 'navigation-bar--*__' + position, angular.element(el)); } }); var pageView = element.inheritedData('ons-page'); if (pageView && !inline) { pageView.registerToolbar(element); } element.data('ons-toolbar', toolbar); }, post: function(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } }; } }; }]); })(); /** * @ngdoc directive * @id toolbar_button * @name ons-toolbar-button * @category toolbar * @modifier outline * [en]A button with an outline.[/en] * [ja]アウトラインをもったボタンを表示します。[/ja] * @description * [en]Button component for ons-toolbar and ons-bottom-toolbar.[/en] * [ja]ons-toolbarあるいはons-bottom-toolbarに設置できるボタン用コンポーネントです。[/ja] * @codepen aHmGL * @guide Addingatoolbar * [en]Adding a toolbar[/en] * [ja]ツールバーの追加[/ja] * @seealso ons-toolbar * [en]ons-toolbar component[/en] * [ja]ons-toolbarコンポーネント[/ja] * @seealso ons-back-button * [en]ons-back-button component[/en] * [ja]ons-back-buttonコンポーネント[/ja] * @seealso ons-toolbar-button * [en]ons-toolbar-button component[/en] * [ja]ons-toolbar-buttonコンポーネント[/ja] * @example * <ons-toolbar> * <div class="left"><ons-toolbar-button>Button</ons-toolbar-button></div> * <div class="center">Title</div> * <div class="right"><ons-toolbar-button><ons-icon icon="ion-navion" size="28px"></ons-icon></ons-toolbar-button></div> * </ons-toolbar> */ /** * @ngdoc attribute * @name var * @type {String} * @description * [en]Variable name to refer this buttom.[/en] * [ja]このボタンを参照するための名前を指定します。[/ja] */ /** * @ngdoc attribute * @name modifier * @type {String} * @description * [en]The appearance of the button.[/en] * [ja]ボタンの表現を指定します。[/ja] */ /** * @ngdoc attribute * @name disabled * @description * [en]Specify if button should be disabled.[/en] * [ja]ボタンを無効化する場合は指定してください。[/ja] */ (function(){ 'use strict'; var module = angular.module('onsen'); module.directive('onsToolbarButton', ['$onsen', 'GenericView', function($onsen, GenericView) { return { restrict: 'E', transclude: true, scope: {}, templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/toolbar_button.tpl', link: { pre: function(scope, element, attrs) { var toolbarButton = new GenericView(scope, element, attrs), innerElement = element[0].querySelector('.toolbar-button'); $onsen.declareVarAttribute(attrs, toolbarButton); element.data('ons-toolbar-button', toolbarButton); scope.$on('$destroy', function() { toolbarButton._events = undefined; $onsen.removeModifierMethods(toolbarButton); element.data('ons-toolbar-button', undefined); element = null; }); var modifierTemplater = $onsen.generateModifierTemplater(attrs); if (attrs.ngController) { throw new Error('This element can\'t accept ng-controller directive.'); } attrs.$observe('disabled', function(value) { if (value === false || typeof value === 'undefined') { innerElement.removeAttribute('disabled'); } else { innerElement.setAttribute('disabled', 'disabled'); } }); scope.modifierTemplater = $onsen.generateModifierTemplater(attrs); $onsen.addModifierMethods(toolbarButton, 'toolbar-button--*', element.children()); element.children('span').addClass(modifierTemplater('toolbar-button--*')); $onsen.cleaner.onDestroy(scope, function() { $onsen.clearComponent({ scope: scope, attrs: attrs, element: element, }); scope = element = attrs = null; }); }, post: function(scope, element, attrs) { $onsen.fireComponentEvent(element[0], 'init'); } } }; }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){ 'use strict'; var module = angular.module('onsen'); var ComponentCleaner = { /** * @param {jqLite} element */ decomposeNode: function(element) { var children = element.remove().children(); for (var i = 0; i < children.length; i++) { ComponentCleaner.decomposeNode(angular.element(children[i])); } }, /** * @param {Attributes} attrs */ destroyAttributes: function(attrs) { attrs.$$element = null; attrs.$$observers = null; }, /** * @param {jqLite} element */ destroyElement: function(element) { element.remove(); }, /** * @param {Scope} scope */ destroyScope: function(scope) { scope.$$listeners = {}; scope.$$watchers = null; scope = null; }, /** * @param {Scope} scope * @param {Function} fn */ onDestroy: function(scope, fn) { var clear = scope.$on('$destroy', function() { clear(); fn.apply(null, arguments); }); } }; module.factory('ComponentCleaner', function() { return ComponentCleaner; }); // override builtin ng-(eventname) directives (function() { var ngEventDirectives = {}; 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' ').forEach( function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return { compile: function($element, attr) { var fn = $parse(attr[directiveName]); return function(scope, element, attr) { var listener = function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }; element.on(name, listener); ComponentCleaner.onDestroy(scope, function() { element.off(name, listener); element = null; ComponentCleaner.destroyScope(scope); scope = null; ComponentCleaner.destroyAttributes(attr); attr = null; }); }; } }; }]; function directiveNormalize(name) { return name.replace(/-([a-z])/g, function(matches) { return matches[1].toUpperCase(); }); } } ); module.config(['$provide', function($provide) { var shift = function($delegate) { $delegate.shift(); return $delegate; }; Object.keys(ngEventDirectives).forEach(function(directiveName) { $provide.decorator(directiveName + 'Directive', ['$delegate', shift]); }); }]); Object.keys(ngEventDirectives).forEach(function(directiveName) { module.directive(directiveName, ngEventDirectives[directiveName]); }); })(); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){ 'use strict'; var util = { init: function() { this.ready = false; }, addBackButtonListener: function(fn) { if (this._ready) { window.document.addEventListener('backbutton', fn, false); } else { window.document.addEventListener('deviceready', function() { window.document.addEventListener('backbutton', fn, false); }); } }, removeBackButtonListener: function(fn) { if (this._ready) { window.document.removeEventListener('backbutton', fn, false); } else { window.document.addEventListener('deviceready', function() { window.document.removeEventListener('backbutton', fn, false); }); } } }; util.init(); /** * Internal service class for framework implementation. */ angular.module('onsen').service('DeviceBackButtonHandler', function() { this._init = function() { if (window.ons.isWebView()) { window.document.addEventListener('deviceready', function() { util._ready = true; }, false); } else { util._ready = true; } this._bindedCallback = this._callback.bind(this); this.enable(); }; this._isEnabled = false; /** * Enable to handle 'backbutton' events. */ this.enable = function() { if (!this._isEnabled) { util.addBackButtonListener(this._bindedCallback); this._isEnabled = true; } }; /** * Disable to handle 'backbutton' events. */ this.disable = function() { if (this._isEnabled) { util.removeBackButtonListener(this._bindedCallback); this._isEnabled = false; } }; /** * Fire a 'backbutton' event manually. */ this.fireDeviceBackButtonEvent = function() { var event = document.createEvent('Event'); event.initEvent('backbutton', true, true); document.dispatchEvent(event); }; this._callback = function() { this._dispatchDeviceBackButtonEvent(); }; /** * @param {jqLite} element * @param {Function} callback */ this.create = function(element, callback) { if (!(element instanceof angular.element().constructor)) { throw new Error('element must be an instance of jqLite'); } if (!(callback instanceof Function)) { throw new Error('callback must be an instance of Function'); } var handler = { _callback: callback, _element: element, disable: function() { this._element.data('device-backbutton-handler', null); }, setListener: function(callback) { this._callback = callback; }, enable: function() { this._element.data('device-backbutton-handler', this); }, isEnabled: function() { return this._element.data('device-backbutton-handler') === this; }, destroy: function() { this._element.data('device-backbutton-handler', null); this._callback = this._element = null; } }; handler.enable(); return handler; }; /** * @param {Object} event */ this._dispatchDeviceBackButtonEvent = function(event) { var tree = this._captureTree(); var element = this._findHandlerLeafElement(tree); //this._dumpTree(tree); //this._dumpParents(element); var handler = element.data('device-backbutton-handler'); handler._callback(createEvent(element)); function createEvent(element) { return { _element: element, callParentHandler: function() { var parent = this._element.parent(); var hander = null; while (parent[0]) { handler = parent.data('device-backbutton-handler'); if (handler) { return handler._callback(createEvent(parent)); } parent = parent.parent(); } } }; } }; this._dumpParents = function(element) { while(element[0]) { console.log(element[0].nodeName.toLowerCase() + '.' + element.attr('class')); element = element.parent(); } }; /** * @return {Object} */ this._captureTree = function() { return createTree(angular.element(document.body)); function createTree(element) { return { element: element, children: Array.prototype.concat.apply([], Array.prototype.map.call(element.children(), function(child) { child = angular.element(child); if (child[0].style.display === 'none') { return []; } if (child.children().length === 0 && !child.data('device-backbutton-handler')) { return []; } var result = createTree(child); if (result.children.length === 0 && !child.data('device-backbutton-handler')) { return []; } return [result]; })) }; } }; this._dumpTree = function(node) { _dump(node, 0); function _dump(node, level) { var pad = new Array(level + 1).join(' '); console.log(pad + node.element[0].nodeName.toLowerCase()); node.children.forEach(function(node) { _dump(node, level + 1); }); } }; /** * @param {Object} tree * @return {jqLite} */ this._findHandlerLeafElement = function(tree) { return find(tree); function find(node) { if (node.children.length === 0) { return node.element; } if (node.children.length === 1) { return find(node.children[0]); } return node.children.map(function(childNode) { return childNode.element; }).reduce(function(left, right) { if (left === null) { return right; } var leftZ = parseInt(window.getComputedStyle(left[0], '').zIndex, 10); var rightZ = parseInt(window.getComputedStyle(right[0], '').zIndex, 10); if (!isNaN(leftZ) && !isNaN(rightZ)) { return leftZ > rightZ ? left : right; } throw new Error('Capturing backbutton-handler is failure.'); }, null); } }; this._init(); }); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){ 'use strict'; var module = angular.module('onsen'); /** * Internal service class for framework implementation. */ module.factory('$onsen', ['$rootScope', '$window', '$cacheFactory', '$document', '$templateCache', '$http', '$q', '$onsGlobal', 'ComponentCleaner', 'DeviceBackButtonHandler', function($rootScope, $window, $cacheFactory, $document, $templateCache, $http, $q, $onsGlobal, ComponentCleaner, DeviceBackButtonHandler) { var unlockerDict = createUnlockerDict(); var $onsen = createOnsenService(); return $onsen; function createOnsenService() { return { DIRECTIVE_TEMPLATE_URL: 'templates', cleaner: ComponentCleaner, DeviceBackButtonHandler: DeviceBackButtonHandler, _defaultDeviceBackButtonHandler: DeviceBackButtonHandler.create(angular.element(document.body), function() { navigator.app.exitApp(); }), getDefaultDeviceBackButtonHandler: function() { return this._defaultDeviceBackButtonHandler; }, /** * @return {Boolean} */ isEnabledAutoStatusBarFill: function() { return !!$onsGlobal._config.autoStatusBarFill; }, /** * @param {HTMLElement} element * @return {Boolean} */ shouldFillStatusBar: function(element) { if (this.isEnabledAutoStatusBarFill() && this.isWebView() && this.isIOS7Above()) { if (!(element instanceof HTMLElement)) { throw new Error('element must be an instance of HTMLElement'); } var debug = element.tagName === 'ONS-TABBAR' ? console.log.bind(console) : angular.noop; for (;;) { if (element.hasAttribute('no-status-bar-fill')) { return false; } element = element.parentNode; debug(element); if (!element || !element.hasAttribute) { return true; } } } return false; }, /** * @param {Object} params * @param {Scope} [params.scope] * @param {jqLite} [params.element] * @param {Array} [params.elements] * @param {Attributes} [params.attrs] */ clearComponent: function(params) { if (params.scope) { ComponentCleaner.destroyScope(params.scope); } if (params.attrs) { ComponentCleaner.destroyAttributes(params.attrs); } if (params.element) { ComponentCleaner.destroyElement(params.element); } if (params.elements) { params.elements.forEach(function(element) { ComponentCleaner.destroyElement(element); }); } }, /** * Find first ancestor of el with tagName * or undefined if not found * * @param {jqLite} element * @param {String} tagName */ upTo : function(el, tagName) { tagName = tagName.toLowerCase(); do { if (!el) { return null; } el = el.parentNode; if (el.tagName.toLowerCase() == tagName) { return el; } } while (el.parentNode); return null; }, /** * @param {Array} dependencies * @param {Function} callback */ waitForVariables: function(dependencies, callback) { unlockerDict.addCallback(dependencies, callback); }, /** * @param {jqLite} element * @param {String} name */ findElementeObject: function(element, name) { return element.inheritedData(name); }, /** * @param {String} page * @return {Promise} */ getPageHTMLAsync: function(page) { var cache = $templateCache.get(page); if (cache) { var deferred = $q.defer(); var html = typeof cache === 'string' ? cache : cache[1]; deferred.resolve(this.normalizePageHTML(html)); return deferred.promise; } else { return $http({ url: page, method: 'GET' }).then(function(response) { var html = response.data; return this.normalizePageHTML(html); }.bind(this)); } }, /** * @param {String} html * @return {String} */ normalizePageHTML: function(html) { html = ('' + html).trim(); if (!html.match(/^<(ons-page|ons-navigator|ons-tabbar|ons-sliding-menu|ons-split-view)/)) { html = '<ons-page>' + html + '</ons-page>'; } return html; }, /** * Create modifier templater function. The modifier templater generate css classes binded modifier name. * * @param {Object} attrs * @param {Array} [modifiers] an array of appendix modifier * @return {Function} */ generateModifierTemplater: function(attrs, modifiers) { var attrModifiers = attrs && typeof attrs.modifier === 'string' ? attrs.modifier.trim().split(/ +/) : []; modifiers = angular.isArray(modifiers) ? attrModifiers.concat(modifiers) : attrModifiers; /** * @return {String} template eg. 'ons-button--*', 'ons-button--*__item' * @return {String} */ return function(template) { return modifiers.map(function(modifier) { return template.replace('*', modifier); }).join(' '); }; }, /** * Add modifier methods to view object. * * @param {Object} view object * @param {String} template * @param {jqLite} element */ addModifierMethods: function(view, template, element) { var _tr = function(modifier) { return template.replace('*', modifier); }; var fns = { hasModifier: function(modifier) { return element.hasClass(_tr(modifier)); }, removeModifier: function(modifier) { element.removeClass(_tr(modifier)); }, addModifier: function(modifier) { element.addClass(_tr(modifier)); }, setModifier: function(modifier) { var classes = element.attr('class').split(/\s+/), patt = template.replace('*', '.'); for (var i=0; i < classes.length; i++) { var cls = classes[i]; if (cls.match(patt)) { element.removeClass(cls); } } element.addClass(_tr(modifier)); }, toggleModifier: function(modifier) { var cls = _tr(modifier); if (element.hasClass(cls)) { element.removeClass(cls); } else { element.addClass(cls); } } }; var append = function(oldFn, newFn) { if (typeof oldFn !== 'undefined') { return function() { return oldFn.apply(null, arguments) || newFn.apply(null, arguments); }; } else { return newFn; } }; view.hasModifier = append(view.hasModifier, fns.hasModifier); view.removeModifier = append(view.removeModifier, fns.removeModifier); view.addModifier = append(view.addModifier, fns.addModifier); view.setModifier = append(view.setModifier, fns.setModifier); view.toggleModifier = append(view.toggleModifier, fns.toggleModifier); }, /** * Remove modifier methods. * * @param {Object} view object */ removeModifierMethods: function(view) { view.hasModifier = view.removeModifier = view.addModifier = view.setModifier = view.toggleModifier = undefined; }, /** * Define a variable to JavaScript global scope and AngularJS scope as 'var' attribute name. * * @param {Object} attrs * @param object */ declareVarAttribute: function(attrs, object) { if (typeof attrs['var'] === 'string') { var varName = attrs['var']; this._defineVar(varName, object); unlockerDict.unlockVarName(varName); } }, _registerEventHandler: function(component, eventName) { var capitalizedEventName = eventName.charAt(0).toUpperCase() + eventName.slice(1); component.on(eventName, function(event) { $onsen.fireComponentEvent(component._element[0], eventName, event); var handler = component._attrs['ons' + capitalizedEventName]; if (handler) { component._scope.$eval(handler, {$event: event}); component._scope.$evalAsync(); } }); }, /** * Register event handlers for attributes. * * @param {Object} component * @param {String} eventNames */ registerEventHandlers: function(component, eventNames) { eventNames = eventNames.trim().split(/\s+/); for (var i = 0, l = eventNames.length; i < l; i ++) { var eventName = eventNames[i]; this._registerEventHandler(component, eventName); } }, /** * @return {Boolean} */ isAndroid: function() { return !!window.navigator.userAgent.match(/android/i); }, /** * @return {Boolean} */ isIOS: function() { return !!window.navigator.userAgent.match(/(ipad|iphone|ipod touch)/i); }, /** * @return {Boolean} */ isWebView: function() { return window.ons.isWebView(); }, /** * @return {Boolean} */ isIOS7Above: (function() { var ua = window.navigator.userAgent; var match = ua.match(/(iPad|iPhone|iPod touch);.*CPU.*OS (\d+)_(\d+)/i); var result = match ? parseFloat(match[2] + '.' + match[3]) >= 7 : false; return function() { return result; }; })(), /** * Fire a named event for a component. The view object, if it exists, is attached to event.component. * * @param {HTMLElement} [dom] * @param {String} event name */ fireComponentEvent: function(dom, eventName, data) { data = data || {}; var event = document.createEvent('HTMLEvents'); for (var key in data) { if (data.hasOwnProperty(key)) { event[key] = data[key]; } } event.component = dom ? angular.element(dom).data(dom.nodeName.toLowerCase()) || null : null; event.initEvent(dom.nodeName.toLowerCase() + ':' + eventName, true, true); dom.dispatchEvent(event); }, /** * Define a variable to JavaScript global scope and AngularJS scope. * * Util.defineVar('foo', 'foo-value'); * // => window.foo and $scope.foo is now 'foo-value' * * Util.defineVar('foo.bar', 'foo-bar-value'); * // => window.foo.bar and $scope.foo.bar is now 'foo-bar-value' * * @param {String} name * @param object */ _defineVar: function(name, object) { var names = name.split(/\./); function set(container, names, object) { var name; for (var i = 0; i < names.length - 1; i++) { name = names[i]; if (container[name] === undefined || container[name] === null) { container[name] = {}; } container = container[name]; } container[names[names.length - 1]] = object; if (container[names[names.length -1]] !== object) { throw new Error('Cannot set var="' + object._attrs.var + '" because it will overwrite a read-only variable.'); } } if (ons.componentBase) { set(ons.componentBase, names, object); } set($rootScope, names, object); } }; } function createUnlockerDict() { return { _unlockersDict: {}, _unlockedVarDict: {}, /** * @param {String} name * @param {Function} unlocker */ _addVarLock: function (name, unlocker) { if (!(unlocker instanceof Function)) { throw new Error('unlocker argument must be an instance of Function.'); } if (this._unlockersDict[name]) { this._unlockersDict[name].push(unlocker); } else { this._unlockersDict[name] = [unlocker]; } }, /** * @param {String} varName */ unlockVarName: function(varName) { var unlockers = this._unlockersDict[varName]; if (unlockers) { unlockers.forEach(function(unlock) { unlock(); }); } this._unlockedVarDict[varName] = true; }, /** * @param {Array} dependencies an array of var name * @param {Function} callback */ addCallback: function(dependencies, callback) { if (!(callback instanceof Function)) { throw new Error('callback argument must be an instance of Function.'); } var doorLock = new DoorLock(); var self = this; dependencies.forEach(function(varName) { if (!self._unlockedVarDict[varName]) { // wait for variable declaration var unlock = doorLock.lock(); self._addVarLock(varName, unlock); } }); if (doorLock.isLocked()) { doorLock.waitUnlock(callback); } else { callback(); } } }; } }]); })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Minimal animation library for managing css transition on mobile browsers. */ window.animit = (function(){ 'use strict'; /** * @param {HTMLElement} element */ var Animit = function(element) { if (!(this instanceof Animit)) { return new Animit(element); } if (element instanceof HTMLElement) { this.elements = [element]; } else if (Object.prototype.toString.call(element) === '[object Array]') { this.elements = element; } else { throw new Error('First argument must be an array or an instance of HTMLElement.'); } this.transitionQueue = []; this.lastStyleAttributeDict = []; var self = this; this.elements.forEach(function(element, index) { if (!element.hasAttribute('data-animit-orig-style')) { self.lastStyleAttributeDict[index] = element.getAttribute('style'); element.setAttribute('data-animit-orig-style', self.lastStyleAttributeDict[index] || ''); } else { self.lastStyleAttributeDict[index] = element.getAttribute('data-animit-orig-style'); } }); }; Animit.prototype = { /** * @property {Array} */ transitionQueue: undefined, /** * @property {HTMLElement} */ element: undefined, /** * Start animation sequence with passed animations. * * @param {Function} callback */ play: function(callback) { if (typeof callback === 'function') { this.transitionQueue.push(function(done) { callback(); done(); }); } this.startAnimation(); return this; }, /** * Queue transition animations or other function. * * e.g. animit(elt).queue({color: 'red'}) * e.g. animit(elt).queue({color: 'red'}, {duration: 0.4}) * e.g. animit(elt).queue({css: {color: 'red'}, duration: 0.2}) * * @param {Object|Animit.Transition|Function} transition * @param {Object} [options] */ queue: function(transition, options) { var queue = this.transitionQueue; if (transition && options) { options.css = transition; transition = new Animit.Transition(options); } if (!(transition instanceof Function || transition instanceof Animit.Transition)) { if (transition.css) { transition = new Animit.Transition(transition); } else { transition = new Animit.Transition({ css: transition }); } } if (transition instanceof Function) { queue.push(transition); } else if (transition instanceof Animit.Transition) { queue.push(transition.build()); } else { throw new Error('Invalid arguments'); } return this; }, /** * Queue transition animations. * * @param {Float} seconds */ wait: function(seconds) { var self = this; this.transitionQueue.push(function(done) { setTimeout(done, 1000 * seconds); }); return this; }, /** * Reset element's style. * * @param {Object} [options] * @param {Float} [options.duration] * @param {String} [options.timing] * @param {String} [options.transition] */ resetStyle: function(options) { options = options || {}; var self = this; if (options.transition && !options.duration) { throw new Error('"options.duration" is required when "options.transition" is enabled.'); } if (options.transition || (options.duration && options.duration > 0)) { var transitionValue = options.transition || ('all ' + options.duration + 's ' + (options.timing || 'linear')); var transitionStyle = 'transition: ' + transitionValue + '; -' + Animit.prefix + '-transition: ' + transitionValue + ';'; this.transitionQueue.push(function(done) { var elements = this.elements; // transition and style settings elements.forEach(function(element, index) { element.style[Animit.prefix + 'Transition'] = transitionValue; element.style.transition = transitionValue; var styleValue = (self.lastStyleAttributeDict[index] ? self.lastStyleAttributeDict[index] + '; ' : '') + transitionStyle; element.setAttribute('style', styleValue); }); // add "transitionend" event handler var removeListeners = util.addOnTransitionEnd(elements[0], function() { clearTimeout(timeoutId); reset(); done(); }); // for fail safe. var timeoutId = setTimeout(function() { removeListeners(); reset(); done(); }, options.duration * 1000 * 1.4); }); } else { this.transitionQueue.push(function(done) { reset(); done(); }); } return this; function reset() { // Clear transition animation settings. self.elements.forEach(function(element, index) { element.style[Animit.prefix + 'Transition'] = 'none'; element.style.transition = 'none'; if (self.lastStyleAttributeDict[index]) { element.setAttribute('style', self.lastStyleAttributeDict[index]); } else { element.setAttribute('style', ''); element.removeAttribute('style'); } }); } }, /** * Start animation sequence. */ startAnimation: function() { this._dequeueTransition(); return this; }, _dequeueTransition: function() { var transition = this.transitionQueue.shift(); if (this._currentTransition) { throw new Error('Current transition exists.'); } this._currentTransition = transition; var self = this; var called = false; var done = function() { if (!called) { called = true; self._currentTransition = undefined; self._dequeueTransition(); } else { throw new Error('Invalid state: This callback is called twice.'); } }; if (transition) { transition.call(this, done); } } }; Animit.cssPropertyDict = (function() { var styles = window.getComputedStyle(document.documentElement, ''); var dict = {}; var a = 'A'.charCodeAt(0); var z = 'z'.charCodeAt(0); for (var key in styles) { if (styles.hasOwnProperty(key)) { var char = key.charCodeAt(0); if (a <= key.charCodeAt(0) && z >= key.charCodeAt(0)) { if (key !== 'cssText' && key !== 'parentText' && key !== 'length') { dict[key] = true; } } } } return dict; })(); Animit.hasCssProperty = function(name) { return !!Animit.cssPropertyDict[name]; }; /** * Vendor prefix for css property. */ Animit.prefix = (function() { var styles = window.getComputedStyle(document.documentElement, ''), pre = (Array.prototype.slice .call(styles) .join('') .match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o']) )[1]; return pre; })(); /** * @param {Animit} arguments */ Animit.runAll = function(/* arguments... */) { for (var i = 0; i < arguments.length; i++) { arguments[i].play(); } }; /** * @param {Object} options * @param {Float} [options.duration] * @param {String} [options.property] * @param {String} [options.timing] */ Animit.Transition = function(options) { this.options = options || {}; this.options.duration = this.options.duration || 0; this.options.timing = this.options.timing || 'linear'; this.options.css = this.options.css || {}; this.options.property = this.options.property || 'all'; }; Animit.Transition.prototype = { /** * @param {HTMLElement} element * @return {Function} */ build: function() { if (Object.keys(this.options.css).length === 0) { throw new Error('options.css is required.'); } var css = createActualCssProps(this.options.css); if (this.options.duration > 0) { var transitionValue = util.buildTransitionValue(this.options); var self = this; return function(callback) { var elements = this.elements; var timeout = self.options.duration * 1000 * 1.4; var removeListeners = util.addOnTransitionEnd(elements[0], function() { clearTimeout(timeoutId); callback(); }); var timeoutId = setTimeout(function() { removeListeners(); callback(); }, timeout); elements.forEach(function(element, index) { element.style[Animit.prefix + 'Transition'] = transitionValue; element.style.transition = transitionValue; Object.keys(css).forEach(function(name) { element.style[name] = css[name]; }); }); }; } if (this.options.duration <= 0) { return function(callback) { var elements = this.elements; elements.forEach(function(element, index) { element.style[Animit.prefix + 'Transition'] = 'none'; element.transition = 'none'; Object.keys(css).forEach(function(name) { element.style[name] = css[name]; }); }); if (elements.length) { elements[0].offsetHeight; } if (window.requestAnimationFrame) { requestAnimationFrame(callback); } else { setTimeout(callback, 1000 / 30); } }; } function createActualCssProps(css) { var result = {}; Object.keys(css).forEach(function(name) { var value = css[name]; name = util.normalizeStyleName(name); var prefixed = Animit.prefix + util.capitalize(name); if (Animit.cssPropertyDict[name]) { result[name] = value; } else if (Animit.cssPropertyDict[prefixed]) { result[prefixed] = value; } else { result[prefixed] = value; result[name] = value; } }); return result; } } }; var util = { /** * Normalize style property name. */ normalizeStyleName: function(name) { name = name.replace(/-[a-zA-Z]/g, function(all) { return all.slice(1).toUpperCase(); }); return name.charAt(0).toLowerCase() + name.slice(1); }, // capitalize string capitalize : function(str) { return str.charAt(0).toUpperCase() + str.slice(1); }, /** * @param {Object} params * @param {String} params.property * @param {Float} params.duration * @param {String} params.timing */ buildTransitionValue: function(params) { params.property = params.property || 'all'; params.duration = params.duration || 0.4; params.timing = params.timing || 'linear'; var props = params.property.split(/ +/); return props.map(function(prop) { return prop + ' ' + params.duration + 's ' + params.timing; }).join(', '); }, /** * Add an event handler on "transitionend" event. */ addOnTransitionEnd: function(element, callback) { if (!element) { return function() {}; } var fn = function(event) { if (element == event.target) { event.stopPropagation(); removeListeners(); callback(); } }; var removeListeners = function() { util._transitionEndEvents.forEach(function(eventName) { element.removeEventListener(eventName, fn); }); }; util._transitionEndEvents.forEach(function(eventName) { element.addEventListener(eventName, fn, false); }); return removeListeners; }, _transitionEndEvents: (function() { if (Animit.prefix === 'webkit' || Animit.prefix === 'o' || Animit.prefix === 'moz' || Animit.prefix === 'ms') { return [Animit.prefix + 'TransitionEnd', 'transitionend']; } return ['transitionend']; })() }; return Animit; })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @ngdoc object * @name ons.notification * @category dialog * @codepen Qwwxyp * @description * [en]Utility methods to create different kinds of alert dialogs. There are three methods available: alert, confirm and prompt.[/en] * [ja]いくつかの種類のアラートダイアログを作成するためのユーティリティメソッドを収めたオブジェクトです。[/ja] * @example * <script> * ons.notification.alert({ * message: 'Hello, world!' * }); * * ons.notification.confirm({ * message: 'Are you ready?' * callback: function(answer) { * // Do something here. * } * }); * * ons.notification.prompt({ * message: 'How old are you?', * callback: function(age) { * ons.notification.alert({ * message: 'You are ' + age + ' years old.' * }); * }); * }); * </script> */ /** * @ngdoc method * @signature alert(options) * @param {Object} options * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクトです。[/ja] * @param {String} [options.message] * [en]Alert message.[/en] * [ja]アラートダイアログに表示する文字列を指定します。[/ja] * @param {String} [options.messageHTML] * [en]Alert message in HTML.[/en] * [ja]アラートダイアログに表示するHTMLを指定します。[/ja] * @param {String} [options.buttonLabel] * [en]Label for confirmation button. Default is "OK".[/en] * [ja]確認ボタンのラベルを指定します。"OK"がデフォルトです。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none", "fade" and "slide".[/en] * [ja]アラートダイアログを表示する際のアニメーション名を指定します。"none", "fade", "slide"のいずれかを指定できます。[/ja] * @param {String} [options.title] * [en]Dialog title. Default is "Alert".[/en] * [ja]アラートダイアログの上部に表示するタイトルを指定します。"Alert"がデフォルトです。[/ja] * @param {String} [options.modifier] * [en]Modifier for the dialog.[/en] * [ja]アラートダイアログのmodifier属性の値を指定します。[/ja] * @param {Function} [options.callback] * [en]Function that executes after dialog has been closed.[/en] * [ja]アラートダイアログが閉じられた時に呼び出される関数オブジェクトを指定します。[/ja] * @description * [en] * Display an alert dialog to show the user a message. * The content of the message can be either simple text or HTML. * Must specify either message or messageHTML. * [/en] * [ja] * ユーザーへメッセージを見せるためのアラートダイアログを表示します。 * 表示するメッセージは、テキストかもしくはHTMLを指定できます。 * このメソッドの引数には、options.messageもしくはoptions.messageHTMLのどちらかを必ず指定する必要があります。 * [/ja] */ /** * @ngdoc method * @signature confirm(options) * @param {Object} options * [en]Parameter object.[/en] * @param {String} [options.message] * [en]Confirmation question.[/en] * [ja]確認ダイアログに表示するメッセージを指定します。[/ja] * @param {String} [options.messageHTML] * [en]Dialog content in HTML.[/en] * [ja]確認ダイアログに表示するHTMLを指定します。[/ja] * @param {Array} [options.buttonLabels] * [en]Labels for the buttons. Default is ["Cancel", "OK"].[/en] * [ja]ボタンのラベルの配列を指定します。["Cancel", "OK"]がデフォルトです。[/ja] * @param {Number} [options.primaryButtonIndex] * [en]Index of primary button. Default is 1.[/en] * [ja]プライマリボタンのインデックスを指定します。デフォルトは 1 です。[/ja] * @param {Boolean} [options.cancelable] * [en]Whether the dialog is cancelable or not. Default is false.[/en] * [ja]ダイアログがキャンセル可能かどうかを指定します。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none", "fade" and "slide".[/en] * [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定します。[/ja] * @param {String} [options.title] * [en]Dialog title. Default is "Confirm".[/en] * [ja]ダイアログのタイトルを指定します。"Confirm"がデフォルトです。[/ja] * @param {String} [options.modifier] * [en]Modifier for the dialog.[/en] * [ja]ダイアログのmodifier属性の値を指定します。[/ja] * @param {Function} [options.callback] * [en] * Function that executes after the dialog has been closed. * Argument for the function is the index of the button that was pressed or -1 if the dialog was canceled. * [/en] * [ja] * ダイアログが閉じられた後に呼び出される関数オブジェクトを指定します。 * この関数の引数として、押されたボタンのインデックス値が渡されます。 * もしダイアログがキャンセルされた場合には-1が渡されます。 * [/ja] * @description * [en] * Display a dialog to ask the user for confirmation. * The default button labels are "Cancel" and "OK" but they can be customized. * Must specify either message or messageHTML. * [/en] * [ja] * ユーザに確認を促すダイアログを表示します。 * デオルとのボタンラベルは、"Cancel"と"OK"ですが、これはこのメソッドの引数でカスタマイズできます。 * このメソッドの引数には、options.messageもしくはoptions.messageHTMLのどちらかを必ず指定する必要があります。 * [/ja] */ /** * @ngdoc method * @signature prompt(options) * @param {Object} options * [en]Parameter object.[/en] * [ja]オプションを指定するオブジェクトです。[/ja] * @param {String} [options.message] * [en]Prompt question.[/en] * [ja]ダイアログに表示するメッセージを指定します。[/ja] * @param {String} [options.messageHTML] * [en]Dialog content in HTML.[/en] * [ja]ダイアログに表示するHTMLを指定します。[/ja] * @param {String} [options.buttonLabel] * [en]Label for confirmation button. Default is "OK".[/en] * [ja]確認ボタンのラベルを指定します。"OK"がデフォルトです。[/ja] * @param {Number} [options.primaryButtonIndex] * [en]Index of primary button. Default is 1.[/en] * [ja]プライマリボタンのインデックスを指定します。デフォルトは 1 です。[/ja] * @param {Boolean} [options.cancelable] * [en]Whether the dialog is cancelable or not. Default is false.[/en] * [ja]ダイアログがキャンセル可能かどうかを指定します。デフォルトは false です。[/ja] * @param {String} [options.animation] * [en]Animation name. Available animations are "none", "fade" and "slide".[/en] * [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定します。[/ja] * @param {String} [options.title] * [en]Dialog title. Default is "Alert".[/en] * [ja]ダイアログのタイトルを指定します。デフォルトは "Alert" です。[/ja] * @param {String} [options.modifier] * [en]Modifier for the dialog.[/en] * [ja]ダイアログのmodifier属性の値を指定します。[/ja] * @param {Function} [options.callback] * [en] * Function that executes after the dialog has been closed. * Argument for the function is the value of the input field or null if the dialog was canceled. * [/en] * [ja] * ダイアログが閉じられた後に実行される関数オブジェクトを指定します。 * 関数の引数として、インプット要素の中の値が渡されます。ダイアログがキャンセルされた場合には、nullが渡されます。 * [/ja] * @description * [en] * Display a dialog with a prompt to ask the user a question. * Must specify either message or messageHTML. * [/en] * [ja] * ユーザーに入力を促すダイアログを表示します。 * このメソッドの引数には、options.messageもしくはoptions.messageHTMLのどちらかを必ず指定する必要があります。 * [/ja] */ window.ons.notification = (function() { var createAlertDialog = function(title, message, buttonLabels, primaryButtonIndex, modifier, animation, callback, messageIsHTML, cancelable, promptDialog, autofocus, placeholder) { var dialogEl = angular.element('<ons-alert-dialog>'), titleEl = angular.element('<div>').addClass('alert-dialog-title').text(title), messageEl = angular.element('<div>').addClass('alert-dialog-content'), footerEl = angular.element('<div>').addClass('alert-dialog-footer'), inputEl; if (modifier) { dialogEl.attr('modifier', modifier); } dialogEl.attr('animation', animation); if (messageIsHTML) { messageEl.html(message); } else { messageEl.text(message); } dialogEl.append(titleEl).append(messageEl); if (promptDialog) { inputEl = angular.element('<input>') .addClass('text-input') .attr('placeholder', placeholder) .css({width: '100%', marginTop: '10px'}); messageEl.append(inputEl); } dialogEl.append(footerEl); angular.element(document.body).append(dialogEl); ons.$compile(dialogEl)(dialogEl.injector().get('$rootScope')); var alertDialog = dialogEl.data('ons-alert-dialog'); if (buttonLabels.length <= 2) { footerEl.addClass('alert-dialog-footer--one'); } var createButton = function(i) { var buttonEl = angular.element('<button>').addClass('alert-dialog-button').text(buttonLabels[i]); if (i == primaryButtonIndex) { buttonEl.addClass('alert-dialog-button--primal'); } if (buttonLabels.length <= 2) { buttonEl.addClass('alert-dialog-button--one'); } buttonEl.on('click', function() { buttonEl.off('click'); alertDialog.hide({ callback: function() { if (promptDialog) { callback(inputEl.val()); } else { callback(i); } alertDialog.destroy(); alertDialog = inputEl = buttonEl = null; } }); }); footerEl.append(buttonEl); }; for (var i = 0; i < buttonLabels.length; i++) { createButton(i); } if (cancelable) { alertDialog.setCancelable(cancelable); alertDialog.on('cancel', function() { if(promptDialog) { callback(null); } else { callback(-1); } setTimeout(function() { alertDialog.destroy(); alertDialog = null; inputEl = null; }); }); } alertDialog.show({ callback: function() { if(promptDialog && autofocus) { inputEl[0].focus(); } } }); dialogEl = titleEl = messageEl = footerEl = null; }; return { /** * @param {Object} options * @param {String} [options.message] * @param {String} [options.messageHTML] * @param {String} [options.buttonLabel] * @param {String} [options.animation] * @param {String} [options.title] * @param {String} [options.modifier] * @param {Function} [options.callback] */ alert: function(options) { var defaults = { buttonLabel: 'OK', animation: 'default', title: 'Alert', callback: function() {} }; options = angular.extend({}, defaults, options); if (!options.message && !options.messageHTML) { throw new Error('Alert dialog must contain a message.'); } createAlertDialog( options.title, options.message || options.messageHTML, [options.buttonLabel], 0, options.modifier, options.animation, options.callback, !options.message ? true : false, false, false, false ); }, /** * @param {Object} options * @param {String} [options.message] * @param {String} [options.messageHTML] * @param {Array} [options.buttonLabels] * @param {Number} [options.primaryButtonIndex] * @param {Boolean} [options.cancelable] * @param {String} [options.animation] * @param {String} [options.title] * @param {String} [options.modifier] * @param {Function} [options.callback] */ confirm: function(options) { var defaults = { buttonLabels: ['Cancel', 'OK'], primaryButtonIndex: 1, animation: 'default', title: 'Confirm', callback: function() {}, cancelable: false }; options = angular.extend({}, defaults, options); if (!options.message && !options.messageHTML) { throw new Error('Confirm dialog must contain a message.'); } createAlertDialog( options.title, options.message || options.messageHTML, options.buttonLabels, options.primaryButtonIndex, options.modifier, options.animation, options.callback, !options.message ? true : false, options.cancelable, false, false ); }, /** * @param {Object} options * @param {String} [options.message] * @param {String} [options.messageHTML] * @param {String} [options.buttonLabel] * @param {Boolean} [options.cancelable] * @param {String} [options.animation] * @param {String} [options.placeholder] * @param {String} [options.title] * @param {String} [options.modifier] * @param {Function} [options.callback] * @param {Boolean} [options.autofocus] */ prompt: function(options) { var defaults = { buttonLabel: 'OK', animation: 'default', title: 'Alert', placeholder: '', callback: function() {}, cancelable: false, autofocus: true, }; options = angular.extend({}, defaults, options); if (!options.message && !options.messageHTML) { throw new Error('Prompt dialog must contain a message.'); } createAlertDialog( options.title, options.message || options.messageHTML, [options.buttonLabel], 0, options.modifier, options.animation, options.callback, !options.message ? true : false, options.cancelable, true, options.autofocus, options.placeholder ); } }; })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @ngdoc object * @name ons.orientation * @category util * @description * [en]Utility methods for orientation detection.[/en] * [ja]画面のオリエンテーション検知のためのユーティリティメソッドを収めているオブジェクトです。[/ja] */ /** * @ngdoc event * @name change * @description * [en]Fired when the device orientation changes.[/en] * [ja]デバイスのオリエンテーションが変化した際に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクトです。[/ja] * @param {Boolean} event.isPortrait * [en]Will be true if the current orientation is portrait mode.[/en] * [ja]現在のオリエンテーションがportraitの場合にtrueを返します。[/ja] */ /** * @ngdoc method * @signature isPortrait() * @return {Boolean} * [en]Will be true if the current orientation is portrait mode.[/en] * [ja]オリエンテーションがportraitモードの場合にtrueになります。[/ja] * @description * [en]Returns whether the current screen orientation is portrait or not.[/en] * [ja]オリエンテーションがportraitモードかどうかを返します。[/ja] */ /** * @ngdoc method * @signature isLandscape() * @return {Boolean} * [en]Will be true if the current orientation is landscape mode.[/en] * [ja]オリエンテーションがlandscapeモードの場合にtrueになります。[/ja] * @description * [en]Returns whether the current screen orientation is landscape or not.[/en] * [ja]オリエンテーションがlandscapeモードかどうかを返します。[/ja] */ /** * @ngdoc method * @signature on(eventName, listener) * @description * [en]Add an event listener.[/en] * [ja]イベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature once(eventName, listener) * @description * [en]Add an event listener that's only triggered once.[/en] * [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja] */ /** * @ngdoc method * @signature off(eventName, [listener]) * @description * [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en] * [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja] * @param {String} eventName * [en]Name of the event.[/en] * [ja]イベント名を指定します。[/ja] * @param {Function} listener * [en]Function to execute when the event is triggered.[/en] * [ja]削除するイベントリスナーを指定します。[/ja] */ window.ons.orientation = (function() { return create()._init(); function create() { var obj = { // actual implementation to detect if whether current screen is portrait or not _isPortrait: false, /** * @return {Boolean} */ isPortrait: function() { return this._isPortrait(); }, /** * @return {Boolean} */ isLandscape: function() { return !this.isPortrait(); }, _init: function() { document.addEventListener('DOMContentLoaded', this._onDOMContentLoaded.bind(this), false); if ('orientation' in window) { window.addEventListener('orientationchange', this._onOrientationChange.bind(this), false); } else { window.addEventListener('resize', this._onResize.bind(this), false); } this._isPortrait = function() { return window.innerHeight > window.innerWidth; }; return this; }, _onDOMContentLoaded: function() { this._installIsPortraitImplementation(); this.emit('change', {isPortrait: this.isPortrait()}); }, _installIsPortraitImplementation: function() { var isPortrait = window.innerWidth < window.innerHeight; if (!('orientation' in window)) { this._isPortrait = function() { return window.innerHeight > window.innerWidth; }; } else if (window.orientation % 180 === 0) { this._isPortrait = function() { return Math.abs(window.orientation % 180) === 0 ? isPortrait : !isPortrait; }; } else { this._isPortrait = function() { return Math.abs(window.orientation % 180) === 90 ? isPortrait : !isPortrait; }; } }, _onOrientationChange: function() { var isPortrait = this._isPortrait(); // Wait for the dimensions to change because // of Android inconsistency. var nIter = 0; var interval = setInterval(function() { nIter++; var w = window.innerWidth, h = window.innerHeight; if ((isPortrait && w <= h) || (!isPortrait && w >= h)) { this.emit('change', {isPortrait: isPortrait}); clearInterval(interval); } else if (nIter === 50) { this.emit('change', {isPortrait: isPortrait}); clearInterval(interval); } }.bind(this), 20); }, // Run on not mobile browser. _onResize: function() { this.emit('change', {isPortrait: this.isPortrait()}); } }; MicroEvent.mixin(obj); return obj; } })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @ngdoc object * @name ons.platform * @category util * @description * [en]Utility methods to detect current platform.[/en] * [ja]現在実行されているプラットフォームを検知するためのユーティリティメソッドを収めたオブジェクトです。[/ja] */ /** * @ngdoc method * @signature isWebView() * @description * [en]Returns whether app is running in Cordova.[/en] * [ja]Cordova内で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isIOS() * @description * [en]Returns whether the OS is iOS.[/en] * [ja]iOS上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isAndroid() * @description * [en]Returns whether the OS is Android.[/en] * [ja]Android上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isIPhone() * @description * [en]Returns whether the device is iPhone.[/en] * [ja]iPhone上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isIPad() * @description * [en]Returns whether the device is iPad.[/en] * [ja]iPad上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isBlackBerry() * @description * [en]Returns whether the device is BlackBerry.[/en] * [ja]BlackBerry上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isOpera() * @description * [en]Returns whether the browser is Opera.[/en] * [ja]Opera上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isFirefox() * @description * [en]Returns whether the browser is Firefox.[/en] * [ja]Firefox上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isSafari() * @description * [en]Returns whether the browser is Safari.[/en] * [ja]Safari上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isChrome() * @description * [en]Returns whether the browser is Chrome.[/en] * [ja]Chrome上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isIE() * @description * [en]Returns whether the browser is Internet Explorer.[/en] * [ja]Internet Explorer上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ /** * @ngdoc method * @signature isIOS7above() * @description * [en]Returns whether the iOS version is 7 or above.[/en] * [ja]iOS7以上で実行されているかどうかを返します。[/ja] * @return {Boolean} */ (function() { 'use strict'; window.ons.platform = { /** * @return {Boolean} */ isWebView: function() { return ons.isWebView(); }, /** * @return {Boolean} */ isIOS: function() { return /iPhone|iPad|iPod/i.test(navigator.userAgent); }, /** * @return {Boolean} */ isAndroid: function() { return /Android/i.test(navigator.userAgent); }, /** * @return {Boolean} */ isIPhone: function() { return /iPhone/i.test(navigator.userAgent); }, /** * @return {Boolean} */ isIPad: function() { return /iPad/i.test(navigator.userAgent); }, /** * @return {Boolean} */ isBlackBerry: function() { return /BlackBerry|RIM Tablet OS|BB10/i.test(navigator.userAgent); }, /** * @return {Boolean} */ isOpera: function() { return (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0); }, /** * @return {Boolean} */ isFirefox: function() { return (typeof InstallTrigger !== 'undefined'); }, /** * @return {Boolean} */ isSafari: function() { return (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0); }, /** * @return {Boolean} */ isChrome: function() { return (!!window.chrome && !(!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0)); }, /** * @return {Boolean} */ isIE: function() { return false || !!document.documentMode; }, /** * @return {Boolean} */ isIOS7above: function() { if(/iPhone|iPad|iPod/i.test(navigator.userAgent)) { var ver = (navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/)||[''])[0].replace(/_/g,'.'); return (parseInt(ver.split('.')[0]) >= 7); } return false; } }; })(); (function() { 'use strict'; // fastclick window.addEventListener('load', function() { FastClick.attach(document.body); }, false); // viewport.js new Viewport().setup(); // modernize Modernizr.testStyles('#modernizr { -webkit-overflow-scrolling:touch }', function(elem, rule) { Modernizr.addTest( 'overflowtouch', window.getComputedStyle && window.getComputedStyle(elem).getPropertyValue('-webkit-overflow-scrolling') == 'touch'); }); // confirm to use jqLite if (window.jQuery && angular.element === window.jQuery) { console.warn('Onsen UI require jqLite. Load jQuery after loading AngularJS to fix this error. jQuery may break Onsen UI behavior.'); } })(); /* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){ 'use strict'; angular.module('onsen').run(['$templateCache', function($templateCache) { var templates = window.document.querySelectorAll('script[type="text/ons-template"]'); for (var i = 0; i < templates.length; i++) { var template = angular.element(templates[i]); var id = template.attr('id'); if (typeof id === 'string') { $templateCache.put(id, template.text()); } } }]); })();
framework/react/react-tutorials/src/demo/app/App.js
yhtml5/YHTML5-Tutorial
import React, { Component } from 'react'; import logo from '../../static/logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
Redux-BookList/src/containers/bookList.js
vivekbharatha/ModernReactWithReduxCourseUdemy
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { selectBook } from './../actions/index'; class BookList extends Component { renderList() { return this.props.books.map((book) => { return ( <li onClick={() => this.props.selectBook(book)} key={book.title} className="list-group-item">{book.title}</li> ) }); } render() { return ( <ul className="list-group col-md-4"> {this.renderList()} </ul> ) } } // Obejct returned from it will be made as props to container function mapStateToProps(state) { return { books: state.books }; } // Object returned from it will be made as props to container function mapDispatchToProps(dispatch) { // When selectBook is called, the result should pass to all reducers return bindActionCreators({ selectBook: selectBook }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(BookList);
internals/templates/utils/injectReducer.js
andyzeli/Bil
import React from 'react'; import PropTypes from 'prop-types'; import hoistNonReactStatics from 'hoist-non-react-statics'; import getInjectors from './reducerInjectors'; /** * Dynamically injects a reducer * * @param {string} key A key of the reducer * @param {function} reducer A reducer that will be injected * */ export default ({ key, reducer }) => (WrappedComponent) => { class ReducerInjector extends React.Component { static WrappedComponent = WrappedComponent; static contextTypes = { store: PropTypes.object.isRequired, }; static displayName = `withReducer(${(WrappedComponent.displayName || WrappedComponent.name || 'Component')})`; componentWillMount() { const { injectReducer } = this.injectors; injectReducer(key, reducer); } injectors = getInjectors(this.context.store); render() { return <WrappedComponent {...this.props} />; } } return hoistNonReactStatics(ReducerInjector, WrappedComponent); };
src/modules/persisted/components/Request-persisted.js
otissv/graphql-guru-ide
import React from 'react'; import autobind from 'class-autobind'; import styled from 'styled-components'; import CodeMirror from 'react-codemirror'; import '../../../../node_modules/codemirror/lib/codemirror.css'; require('codemirror/mode/javascript/javascript'); require('codemirror/addon/fold/foldgutter'); require('codemirror/addon/fold/brace-fold'); require('codemirror/addon/dialog/dialog'); require('codemirror/addon/search/search'); require('codemirror/keymap/sublime'); const PersistedRequest = styled.div` overflow-y: auto; flex: 1; `; export default class PersistedQueryEditor extends React.Component { constructor () { super(...arguments); autobind(this); this.editor = null; this.value = ''; } handleOnchange () { const value = this.editor.getCodeMirror().doc.getValue(); this.props.handleOnChange(value); } render () { const { selectedPersisted } = this.props; return ( <PersistedRequest> <CodeMirror ref={editor => { this.editor = editor; }} autoFocus={true} autoSave={true} onChange={this.handleOnchange} preserveScrollPosition={true} value={selectedPersisted.query} options={{ autoCloseBrackets: true, extraKeys: { 'Ctrl-Left': 'goSubwordLeft', 'Ctrl-Right': 'goSubwordRight', 'Alt-Left': 'goGroupLeft', 'Alt-Right': 'goGroupRight' }, foldGutter: { minFoldSize: 4 }, gutters: ['CodeMirror-foldgutter'], keyMap: 'sublime', lineNumbers: true, matchBrackets: true, mode: 'application/json', json: true, showCursorWhenSelecting: true, tabSize: 2, theme: 'dracula' }} /> </PersistedRequest> ); } }
app/client/src/routes.js
oriondean/foosball-pyramid
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/HttpClient'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
front/app/app/rh-components/rh-BlockLinks.js
nudoru/React-Starter-2-app
import React from 'react'; export const BlockLinkHGroup = ({style = 'white', children}) => <ul className={'block-links-' + style + ' block-links-horizontal'}>{children}</ul>; export const BlockLinkVGroup = ({style = 'white', children}) => <ul className={'block-links-' + style + ' block-links-vertical'}>{children}</ul>; export const BlockLink = ({label, byline, link, children}) => <li><a href={link}>{label}{byline ? <em>{byline}</em> : null}</a>{children ? <span className="children">{children}</span> : null}</li>;
ajax/libs/angular-google-maps/2.0.7/angular-google-maps.js
sympmarc/cdnjs
/*! angular-google-maps 2.0.7 2014-11-04 * AngularJS directives for Google Maps * git: https://github.com/angular-ui/angular-google-maps.git */ (function() { String.prototype.contains = function(value, fromIndex) { return this.indexOf(value, fromIndex) !== -1; }; String.prototype.flare = function(flare) { if (flare == null) { flare = 'uiGmap'; } return flare + this; }; String.prototype.ns = String.prototype.flare; }).call(this); /* Author Nick McCready Intersection of Objects if the arrays have something in common each intersecting object will be returned in an new array. */ (function() { _.intersectionObjects = function(array1, array2, comparison) { var res; if (comparison == null) { comparison = void 0; } res = _.map(array1, (function(_this) { return function(obj1) { return _.find(array2, function(obj2) { if (comparison != null) { return comparison(obj1, obj2); } else { return _.isEqual(obj1, obj2); } }); }; })(this)); return _.filter(res, function(o) { return o != null; }); }; _.containsObject = _.includeObject = function(obj, target, comparison) { if (comparison == null) { comparison = void 0; } if (obj === null) { return false; } return _.any(obj, (function(_this) { return function(value) { if (comparison != null) { return comparison(value, target); } else { return _.isEqual(value, target); } }; })(this)); }; _.differenceObjects = function(array1, array2, comparison) { if (comparison == null) { comparison = void 0; } return _.filter(array1, function(value) { return !_.containsObject(array2, value, comparison); }); }; _.withoutObjects = _.differenceObjects; _.indexOfObject = function(array, item, comparison, isSorted) { var i, length; if (array == null) { return -1; } i = 0; length = array.length; if (isSorted) { if (typeof isSorted === "number") { i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return (array[i] === item ? i : -1); } } while (i < length) { if (comparison != null) { if (comparison(array[i], item)) { return i; } } else { if (_.isEqual(array[i], item)) { return i; } } i++; } return -1; }; _["extends"] = function(arrayOfObjectsToCombine) { return _.reduce(arrayOfObjectsToCombine, function(combined, toAdd) { return _.extend(combined, toAdd); }, {}); }; _.isNullOrUndefined = function(thing) { return _.isNull(thing || _.isUndefined(thing)); }; }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module('uiGmapgoogle-maps.providers', []); angular.module("uiGmapgoogle-maps.wrapped", []); angular.module("uiGmapgoogle-maps.extensions", ["uiGmapgoogle-maps.wrapped", 'uiGmapgoogle-maps.providers']); angular.module("uiGmapgoogle-maps.directives.api.utils", ['uiGmapgoogle-maps.extensions']); angular.module("uiGmapgoogle-maps.directives.api.managers", []); angular.module("uiGmapgoogle-maps.directives.api.options", ["uiGmapgoogle-maps.directives.api.utils"]); angular.module("uiGmapgoogle-maps.directives.api.options.builders", []); angular.module("uiGmapgoogle-maps.directives.api.models.child", ["uiGmapgoogle-maps.directives.api.utils", "uiGmapgoogle-maps.directives.api.options", "uiGmapgoogle-maps.directives.api.options.builders"]); angular.module("uiGmapgoogle-maps.directives.api.models.parent", ["uiGmapgoogle-maps.directives.api.managers", "uiGmapgoogle-maps.directives.api.models.child", 'uiGmapgoogle-maps.providers']); angular.module("uiGmapgoogle-maps.directives.api", ["uiGmapgoogle-maps.directives.api.models.parent"]); angular.module("uiGmapgoogle-maps", ["uiGmapgoogle-maps.directives.api", 'uiGmapgoogle-maps.providers']).factory("uiGmapdebounce", [ "$timeout", function($timeout) { return function(fn) { var nthCall; nthCall = 0; return function() { var argz, later, that; that = this; argz = arguments; nthCall++; later = (function(version) { return function() { if (version === nthCall) { return fn.apply(that, argz); } }; })(nthCall); return $timeout(later, 0, true); }; }; } ]); }).call(this); (function() { angular.module('google-maps.providers'.ns()).factory('MapScriptLoader'.ns(), [ '$q', 'uuid'.ns(), function($q, uuid) { var getScriptUrl, scriptId; scriptId = void 0; getScriptUrl = function(options) { if (options.china) { return 'http://maps.google.cn/maps/api/js?'; } else { return 'https://maps.googleapis.com/maps/api/js?'; } }; return { load: function(options) { var deferred, query, randomizedFunctionName, script; deferred = $q.defer(); if (angular.isDefined(window.google) && angular.isDefined(window.google.maps)) { deferred.resolve(window.google.maps); return deferred.promise; } randomizedFunctionName = options.callback = 'onGoogleMapsReady' + Math.round(Math.random() * 1000); window[randomizedFunctionName] = function() { window[randomizedFunctionName] = null; deferred.resolve(window.google.maps); }; query = _.map(options, function(v, k) { return k + '=' + v; }); if (scriptId) { document.getElementById(scriptId).remove(); } query = query.join('&'); script = document.createElement('script'); scriptId = "ui_gmap_map_load_" + uuid.generate(); script.id = scriptId; script.type = 'text/javascript'; script.src = getScriptUrl(options) + query; document.body.appendChild(script); return deferred.promise; } }; } ]).provider('GoogleMapApi'.ns(), function() { this.options = { china: false, v: '3.17', libraries: '', language: 'en', sensor: 'false' }; this.configure = function(options) { angular.extend(this.options, options); }; this.$get = [ 'MapScriptLoader'.ns(), (function(_this) { return function(loader) { return loader.load(_this.options); }; })(this) ]; return this; }); }).call(this); (function() { angular.module("google-maps.extensions".ns()).service('ExtendGWin'.ns(), function() { return { init: _.once(function() { if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) { return; } google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open; google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close; google.maps.InfoWindow.prototype._isOpen = false; google.maps.InfoWindow.prototype.open = function(map, anchor, recurse) { if (recurse != null) { return; } this._isOpen = true; this._open(map, anchor, true); }; google.maps.InfoWindow.prototype.close = function(recurse) { if (recurse != null) { return; } this._isOpen = false; this._close(true); }; google.maps.InfoWindow.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; /* Do the same for InfoBox TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier */ if (window.InfoBox) { window.InfoBox.prototype._open = window.InfoBox.prototype.open; window.InfoBox.prototype._close = window.InfoBox.prototype.close; window.InfoBox.prototype._isOpen = false; window.InfoBox.prototype.open = function(map, anchor) { this._isOpen = true; this._open(map, anchor); }; window.InfoBox.prototype.close = function() { this._isOpen = false; this._close(); }; window.InfoBox.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; } if (window.MarkerLabel_) { window.MarkerLabel_.prototype.setContent = function() { var content; content = this.marker_.get("labelContent"); if (!content || _.isEqual(this.oldContent, content)) { return; } if (typeof (content != null ? content.nodeType : void 0) === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; this.oldContent = content; } else { this.labelDiv_.innerHTML = ""; this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.eventDiv_.appendChild(content); this.oldContent = content; } }; /* Removes the DIV for the label from the DOM. It also removes all event handlers. This method is called automatically when the marker's <code>setMap(null)</code> method is called. @private */ return window.MarkerLabel_.prototype.onRemove = function() { if (this.labelDiv_.parentNode != null) { this.labelDiv_.parentNode.removeChild(this.labelDiv_); } if (this.eventDiv_.parentNode != null) { this.eventDiv_.parentNode.removeChild(this.eventDiv_); } if (!this.listeners_) { return; } if (!this.listeners_.length) { return; } this.listeners_.forEach(function(l) { return google.maps.event.removeListener(l); }); }; } }) }; }); }).call(this); (function() { angular.module("uiGmapgoogle-maps.directives.api.utils").service("_sync".ns(), [ function() { return { fakePromise: function() { var _cb; _cb = void 0; return { then: function(cb) { return _cb = cb; }, resolve: function() { return _cb.apply(void 0, arguments); } }; } }; } ]).service("uiGmap_async", [ "$timeout", "uiGmapPromise", function($timeout, uiGmapPromise) { var defaultChunkSize, doChunk, each, map, waitOrGo; defaultChunkSize = 20; /* utility to reduce code bloat. The whole point is to check if there is existing synchronous work going on. If so we wait on it. Note: This is fully intended to be mutable (ie existingPiecesObj is getting existingPieces prop slapped on) */ waitOrGo = function(existingPiecesObj, fnPromise) { if (!existingPiecesObj.existingPieces) { return existingPiecesObj.existingPieces = fnPromise(); } else { return existingPiecesObj.existingPieces = existingPiecesObj.existingPieces.then(function() { return fnPromise(); }); } }; /* Author: Nicholas McCready & jfriend00 _async handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui The design of any functionality of _async is to be like lodash/underscore and replicate it but call things asynchronously underneath. Each should be sufficient for most things to be derived from. Optional Asynchronous Chunking via promises. */ doChunk = function(array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index) { var cnt, e, i; try { if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) { cnt = chunkSizeOrDontChunk; } else { cnt = array.length; } i = index; while (cnt-- && i < (array ? array.length : i + 1)) { chunkCb(array[i], i); ++i; } if (array) { if (i < array.length) { index = i; if (chunkSizeOrDontChunk) { if (typeof pauseCb === "function") { pauseCb(); } return $timeout(function() { return doChunk(array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index); }, pauseMilli, false); } } else { return overallD.resolve(); } } } catch (_error) { e = _error; return overallD.reject("error within chunking iterator: " + e); } }; each = function(array, chunk, pauseCb, chunkSizeOrDontChunk, index, pauseMilli) { var overallD, ret; if (chunkSizeOrDontChunk == null) { chunkSizeOrDontChunk = defaultChunkSize; } if (index == null) { index = 0; } if (pauseMilli == null) { pauseMilli = 1; } ret = void 0; overallD = uiGmapPromise.defer(); ret = overallD.promise; if (!pauseMilli) { overallD.reject("pause (delay) must be set from _async!"); return ret; } if (array === void 0 || (array != null ? array.length : void 0) <= 0) { overallD.resolve(); return ret; } doChunk(array, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index); return ret; }; map = function(objs, iterator, pauseCb, chunkSizeOrDontChunk, index, pauseMilli) { var results; results = []; if (!((objs != null) && (objs != null ? objs.length : void 0) > 0)) { return uiGmapPromise.resolve(results); } return each(objs, function(o) { return results.push(iterator(o)); }, pauseCb, chunkSizeOrDontChunk, index, pauseMilli).then(function() { return results; }); }; return { each: each, map: map, waitOrGo: waitOrGo, defaultChunkSize: defaultChunkSize }; } ]); }).call(this); (function() { var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; angular.module("google-maps.directives.api.utils".ns()).factory("BaseObject".ns(), function() { var BaseObject, baseObjectKeywords; baseObjectKeywords = ['extended', 'included']; BaseObject = (function() { function BaseObject() {} BaseObject.extend = function(obj) { var key, value, _ref; for (key in obj) { value = obj[key]; if (__indexOf.call(baseObjectKeywords, key) < 0) { this[key] = value; } } if ((_ref = obj.extended) != null) { _ref.apply(this); } return this; }; BaseObject.include = function(obj) { var key, value, _ref; for (key in obj) { value = obj[key]; if (__indexOf.call(baseObjectKeywords, key) < 0) { this.prototype[key] = value; } } if ((_ref = obj.included) != null) { _ref.apply(this); } return this; }; return BaseObject; })(); return BaseObject; }); }).call(this); /* Useful function callbacks that should be defined at later time. Mainly to be used for specs to verify creation / linking. This is to lead a common design in notifying child stuff. */ (function() { angular.module("google-maps.directives.api.utils".ns()).factory("ChildEvents".ns(), function() { return { onChildCreation: function(child) {} }; }); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).service("CtrlHandle".ns(), [ '$q', function($q) { var CtrlHandle; return CtrlHandle = { handle: function($scope, $element) { $scope.$on('$destroy', function() { return CtrlHandle.handle($scope); }); $scope.deferred = $q.defer(); return { getScope: function() { return $scope; } }; }, mapPromise: function(scope, ctrl) { var mapScope; mapScope = ctrl.getScope(); mapScope.deferred.promise.then(function(map) { return scope.map = map; }); return mapScope.deferred.promise; } }; } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).service("EventsHelper".ns(), [ "Logger".ns(), function($log) { return { setEvents: function(gObject, scope, model, ignores) { if (angular.isDefined(scope.events) && (scope.events != null) && angular.isObject(scope.events)) { return _.compact(_.map(scope.events, function(eventHandler, eventName) { var doIgnore; if (ignores) { doIgnore = _(ignores).contains(eventName); } if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName]) && !doIgnore) { return google.maps.event.addListener(gObject, eventName, function() { return scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments])); }); } })); } }, removeEvents: function(listeners) { return listeners != null ? listeners.forEach(function(l) { return google.maps.event.removeListener(l); }) : void 0; } }; } ]); }).call(this); (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.utils".ns()).factory("FitHelper".ns(), [ "BaseObject".ns(), "Logger".ns(), "_async".ns(), function(BaseObject, $log, _async) { var FitHelper; return FitHelper = (function(_super) { __extends(FitHelper, _super); function FitHelper() { return FitHelper.__super__.constructor.apply(this, arguments); } FitHelper.prototype.fit = function(gMarkers, gMap) { var bounds, everSet; if (gMap && gMarkers && gMarkers.length > 0) { bounds = new google.maps.LatLngBounds(); everSet = false; return _async.each(gMarkers, (function(_this) { return function(gMarker) { if (gMarker) { if (!everSet) { everSet = true; } return bounds.extend(gMarker.getPosition()); } }; })(this)).then(function() { if (everSet) { return gMap.fitBounds(bounds); } }); } }; return FitHelper; })(BaseObject); } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).service("GmapUtil".ns(), [ "Logger".ns(), "$compile", function(Logger, $compile) { var getCoords, getLatitude, getLongitude, validateCoords; getLatitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[1]; } else if (angular.isDefined(value.type) && value.type === "Point") { return value.coordinates[1]; } else { return value.latitude; } }; getLongitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[0]; } else if (angular.isDefined(value.type) && value.type === "Point") { return value.coordinates[0]; } else { return value.longitude; } }; getCoords = function(value) { if (!value) { return; } if (Array.isArray(value) && value.length === 2) { return new google.maps.LatLng(value[1], value[0]); } else if (angular.isDefined(value.type) && value.type === "Point") { return new google.maps.LatLng(value.coordinates[1], value.coordinates[0]); } else { return new google.maps.LatLng(value.latitude, value.longitude); } }; validateCoords = function(coords) { if (angular.isUndefined(coords)) { return false; } if (_.isArray(coords)) { if (coords.length === 2) { return true; } } else if ((coords != null) && (coords != null ? coords.type : void 0)) { if (coords.type === "Point" && _.isArray(coords.coordinates) && coords.coordinates.length === 2) { return true; } } if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) { return true; } return false; }; return { setCoordsFromEvent: function(prevValue, newLatLon) { if (!prevValue) { return; } if (Array.isArray(prevValue) && prevValue.length === 2) { prevValue[1] = newLatLon.lat(); prevValue[0] = newLatLon.lng(); } else if (angular.isDefined(prevValue.type) && prevValue.type === "Point") { prevValue.coordinates[1] = newLatLon.lat(); prevValue.coordinates[0] = newLatLon.lng(); } else { prevValue.latitude = newLatLon.lat(); prevValue.longitude = newLatLon.lng(); } return prevValue; }, getLabelPositionPoint: function(anchor) { var xPos, yPos; if (anchor === void 0) { return void 0; } anchor = /^([-\d\.]+)\s([-\d\.]+)$/.exec(anchor); xPos = parseFloat(anchor[1]); yPos = parseFloat(anchor[2]); if ((xPos != null) && (yPos != null)) { return new google.maps.Point(xPos, yPos); } }, createWindowOptions: function(gMarker, scope, content, defaults) { var options; if ((content != null) && (defaults != null) && ($compile != null)) { options = angular.extend({}, defaults, { content: this.buildContent(scope, defaults, content), position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords) }); if ((gMarker != null) && ((options != null ? options.pixelOffset : void 0) == null)) { if (options.boxClass == null) { } else { options.pixelOffset = { height: 0, width: -2 }; } } return options; } else { if (!defaults) { Logger.error("infoWindow defaults not defined"); if (!content) { return Logger.error("infoWindow content not defined"); } } else { return defaults; } } }, buildContent: function(scope, defaults, content) { var parsed, ret; if (defaults.content != null) { ret = defaults.content; } else { if ($compile != null) { content = content.replace(/^\s+|\s+$/g, ""); parsed = content === '' ? '' : $compile(content)(scope); if (parsed.length > 0) { ret = parsed[0]; } } else { ret = content; } } return ret; }, defaultDelay: 50, isTrue: function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }, isFalse: function(value) { return ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO'].indexOf(value) !== -1; }, getCoords: getCoords, validateCoords: validateCoords, equalCoords: function(coord1, coord2) { return getLatitude(coord1) === getLatitude(coord2) && getLongitude(coord1) === getLongitude(coord2); }, validatePath: function(path) { var array, i, polygon, trackMaxVertices; i = 0; if (angular.isUndefined(path.type)) { if (!Array.isArray(path) || path.length < 2) { return false; } while (i < path.length) { if (!((angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) || (typeof path[i].lat === "function" && typeof path[i].lng === "function"))) { return false; } i++; } return true; } else { if (angular.isUndefined(path.coordinates)) { return false; } if (path.type === "Polygon") { if (path.coordinates[0].length < 4) { return false; } array = path.coordinates[0]; } else if (path.type === "MultiPolygon") { trackMaxVertices = { max: 0, index: 0 }; _.forEach(path.coordinates, function(polygon, index) { if (polygon[0].length > this.max) { this.max = polygon[0].length; return this.index = index; } }, trackMaxVertices); polygon = path.coordinates[trackMaxVertices.index]; array = polygon[0]; if (array.length < 4) { return false; } } else if (path.type === "LineString") { if (path.coordinates.length < 2) { return false; } array = path.coordinates; } else { return false; } while (i < array.length) { if (array[i].length !== 2) { return false; } i++; } return true; } }, convertPathPoints: function(path) { var array, i, latlng, result, trackMaxVertices; i = 0; result = new google.maps.MVCArray(); if (angular.isUndefined(path.type)) { while (i < path.length) { latlng; if (angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) { latlng = new google.maps.LatLng(path[i].latitude, path[i].longitude); } else if (typeof path[i].lat === "function" && typeof path[i].lng === "function") { latlng = path[i]; } result.push(latlng); i++; } } else { array; if (path.type === "Polygon") { array = path.coordinates[0]; } else if (path.type === "MultiPolygon") { trackMaxVertices = { max: 0, index: 0 }; _.forEach(path.coordinates, function(polygon, index) { if (polygon[0].length > this.max) { this.max = polygon[0].length; return this.index = index; } }, trackMaxVertices); array = path.coordinates[trackMaxVertices.index][0]; } else if (path.type === "LineString") { array = path.coordinates; } while (i < array.length) { result.push(new google.maps.LatLng(array[i][1], array[i][0])); i++; } } return result; }, extendMapBounds: function(map, points) { var bounds, i; bounds = new google.maps.LatLngBounds(); i = 0; while (i < points.length) { bounds.extend(points.getAt(i)); i++; } return map.fitBounds(bounds); }, getPath: function(object, key) { var obj; obj = object; _.each(key.split("."), function(value) { if (obj) { return obj = obj[value]; } }); return obj; }, validateBoundPoints: function(bounds) { if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) { return false; } return true; }, convertBoundPoints: function(bounds) { var result; result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude)); return result; }, fitMapBounds: function(map, bounds) { return map.fitBounds(bounds); } }; } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).service("IsReady".ns(), [ '$q', '$timeout', function($q, $timeout) { var ctr, promises, proms; ctr = 0; proms = []; promises = function() { return $q.all(proms); }; return { spawn: function() { var d; d = $q.defer(); proms.push(d.promise); ctr += 1; return { instance: ctr, deferred: d }; }, promises: promises, instances: function() { return ctr; }, promise: function(expect) { var d, ohCrap; if (expect == null) { expect = 1; } d = $q.defer(); ohCrap = function() { return $timeout(function() { if (ctr !== expect) { return ohCrap(); } else { return d.resolve(promises()); } }); }; ohCrap(); return d.promise; }, reset: function() { ctr = 0; return proms.length = 0; } }; } ]); }).call(this); (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapLinked", [ "uiGmapBaseObject", function(BaseObject) { var Linked; Linked = (function(_super) { __extends(Linked, _super); function Linked(scope, element, attrs, ctrls) { this.scope = scope; this.element = element; this.attrs = attrs; this.ctrls = ctrls; } return Linked; })(BaseObject); return Linked; } ]); }).call(this); (function() { angular.module("uiGmapgoogle-maps.directives.api.utils").service("uiGmapLogger", [ "$log", function($log) { return { doLog: false, info: function(msg) { if (this.doLog) { if ($log != null) { return $log.info(msg); } else { return console.info(msg); } } }, log: function(msg) { if (this.doLog) { if ($log != null) { return $log.log(msg); } else { return console.log(msg); } } }, error: function(msg) { if (this.doLog) { if ($log != null) { return $log.error(msg); } else { return console.error(msg); } } }, debug: function(msg) { if (this.doLog) { if ($log != null) { return $log.debug(msg); } else { return console.debug(msg); } } }, warn: function(msg) { if (this.doLog) { if ($log != null) { return $log.warn(msg); } else { return console.warn(msg); } } } }; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.utils".ns()).factory("ModelKey".ns(), [ "BaseObject".ns(), "GmapUtil".ns(), function(BaseObject, GmapUtil) { var ModelKey; return ModelKey = (function(_super) { __extends(ModelKey, _super); function ModelKey(scope) { this.scope = scope; this.getChanges = __bind(this.getChanges, this); this.getProp = __bind(this.getProp, this); this.setIdKey = __bind(this.setIdKey, this); this.modelKeyComparison = __bind(this.modelKeyComparison, this); ModelKey.__super__.constructor.call(this); this.defaultIdKey = "id"; this.idKey = void 0; } ModelKey.prototype.evalModelHandle = function(model, modelKey) { if (model === void 0 || modelKey === void 0) { return void 0; } if (modelKey === 'self') { return model; } else { return GmapUtil.getPath(model, modelKey); } }; ModelKey.prototype.modelKeyComparison = function(model1, model2) { var scope; scope = this.scope.coords != null ? this.scope : this.parentScope; if (scope == null) { throw "No scope or parentScope set!"; } return GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords)); }; ModelKey.prototype.setIdKey = function(scope) { return this.idKey = scope.idKey != null ? scope.idKey : this.defaultIdKey; }; ModelKey.prototype.setVal = function(model, key, newValue) { var thingToSet; thingToSet = this.modelOrKey(model, key); thingToSet = newValue; return model; }; ModelKey.prototype.modelOrKey = function(model, key) { if (key == null) { return; } if (key !== 'self') { return model[key]; } return model; }; ModelKey.prototype.getProp = function(propName, model) { return this.modelOrKey(model, propName); }; /* For the cases were watching a large object we only want to know the list of props that actually changed. Also we want to limit the amount of props we analyze to whitelisted props that are actually tracked by scope. (should make things faster with whitelisted) */ ModelKey.prototype.getChanges = function(now, prev, whitelistedProps) { var c, changes, prop; if (whitelistedProps) { prev = _.pick(prev, whitelistedProps); now = _.pick(now, whitelistedProps); } changes = {}; prop = {}; c = {}; for (prop in now) { if (!prev || prev[prop] !== now[prop]) { if (_.isArray(now[prop])) { changes[prop] = now[prop]; } else if (_.isObject(now[prop])) { c = this.getChanges(now[prop], prev[prop]); if (!_.isEmpty(c)) { changes[prop] = c; } } else { changes[prop] = now[prop]; } } } return changes; }; return ModelKey; })(BaseObject); } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).factory("ModelsWatcher".ns(), [ "Logger".ns(), "_async".ns(), function(Logger, _async) { return { figureOutState: function(idKey, scope, childObjects, comparison, callBack) { var adds, mappedScopeModelIds, removals, updates; adds = []; mappedScopeModelIds = {}; removals = []; updates = []; return _async.each(scope.models, function(m) { var child; if (m[idKey] != null) { mappedScopeModelIds[m[idKey]] = {}; if (childObjects[m[idKey]] == null) { return adds.push(m); } else { child = childObjects[m[idKey]]; if (!comparison(m, child.model)) { return updates.push({ model: m, child: child }); } } } else { return Logger.error(" id missing for model " + (m.toString()) + ",\ncan not use do comparison/insertion"); } }).then((function(_this) { return function() { return _async.each(childObjects.values(), function(c) { var id; if (c == null) { Logger.error("child undefined in ModelsWatcher."); return; } if (c.model == null) { Logger.error("child.model undefined in ModelsWatcher."); return; } id = c.model[idKey]; if (mappedScopeModelIds[id] == null) { return removals.push(c); } }); }; })(this)).then((function(_this) { return function() { return callBack({ adds: adds, removals: removals, updates: updates }); }; })(this)); } }; } ]); }).call(this); (function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapPromise', [ '$q', function($q) { return { defer: function() { return $q.defer(); }, resolve: function() { var d; d = $q.defer(); d.resolve.apply(void 0, arguments); return d.promise; } }; } ]); }).call(this); /* Simple Object Map with a lenght property to make it easy to track length/size */ (function() { var propsToPop, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; propsToPop = ['get', 'put', 'remove', 'values', 'keys', 'length', 'push', 'didValueStateChange', 'didKeyStateChange', 'slice', 'removeAll', 'allVals', 'allKeys', 'stateChanged']; window.PropMap = (function() { function PropMap() { this.removeAll = __bind(this.removeAll, this); this.slice = __bind(this.slice, this); this.push = __bind(this.push, this); this.keys = __bind(this.keys, this); this.values = __bind(this.values, this); this.remove = __bind(this.remove, this); this.put = __bind(this.put, this); this.stateChanged = __bind(this.stateChanged, this); this.get = __bind(this.get, this); this.length = 0; this.didValueStateChange = false; this.didKeyStateChange = false; this.allVals = []; this.allKeys = []; } PropMap.prototype.get = function(key) { return this[key]; }; PropMap.prototype.stateChanged = function() { this.didValueStateChange = true; return this.didKeyStateChange = true; }; PropMap.prototype.put = function(key, value) { if (this.get(key) == null) { this.length++; } this.stateChanged(); return this[key] = value; }; PropMap.prototype.remove = function(key, isSafe) { var value; if (isSafe == null) { isSafe = false; } if (isSafe && !this.get(key)) { return void 0; } value = this[key]; delete this[key]; this.length--; this.stateChanged(); return value; }; PropMap.prototype.values = function() { var all; if (!this.didValueStateChange) { return this.allVals; } all = []; this.keys().forEach((function(_this) { return function(key) { if (_.indexOf(propsToPop, key) === -1) { return all.push(_this[key]); } }; })(this)); all; this.didValueStateChange = false; this.keys(); return this.allVals = all; }; PropMap.prototype.keys = function() { var all, keys; if (!this.didKeyStateChange) { return this.allKeys; } keys = _.keys(this); all = []; _.each(keys, (function(_this) { return function(prop) { if (_.indexOf(propsToPop, prop) === -1) { return all.push(prop); } }; })(this)); this.didKeyStateChange = false; this.values(); return this.allKeys = all; }; PropMap.prototype.push = function(obj, key) { if (key == null) { key = "key"; } return this.put(obj[key], obj); }; PropMap.prototype.slice = function() { return this.keys().map((function(_this) { return function(k) { return _this.remove(k); }; })(this)); }; PropMap.prototype.removeAll = function() { return this.slice(); }; return PropMap; })(); angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropMap", function() { return window.PropMap; }); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).factory("PropertyAction".ns(), [ "Logger".ns(), function(Logger) { var PropertyAction; PropertyAction = function(setterFn, isFirstSet, key) { var self; self = this; this.setIfChange = function(newVal, oldVal) { var callingKey; callingKey = this.exp; if (!_.isEqual(oldVal, newVal || isFirstSet)) { return setterFn(callingKey, newVal); } }; this.sic = this.setIfChange; return this; }; return PropertyAction; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.managers".ns()).factory("ClustererMarkerManager".ns(), [ "Logger".ns(), "FitHelper".ns(), "PropMap".ns(), function($log, FitHelper, PropMap) { var ClustererMarkerManager; ClustererMarkerManager = (function(_super) { __extends(ClustererMarkerManager, _super); ClustererMarkerManager.type = 'ClustererMarkerManager'; function ClustererMarkerManager(gMap, opt_markers, opt_options, opt_events) { var self; this.opt_events = opt_events; this.checkSync = __bind(this.checkSync, this); this.getGMarkers = __bind(this.getGMarkers, this); this.fit = __bind(this.fit, this); this.destroy = __bind(this.destroy, this); this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.add = __bind(this.add, this); ClustererMarkerManager.__super__.constructor.call(this); this.type = ClustererMarkerManager.type; self = this; this.opt_options = opt_options; if ((opt_options != null) && opt_markers === void 0) { this.clusterer = new NgMapMarkerClusterer(gMap, void 0, opt_options); } else if ((opt_options != null) && (opt_markers != null)) { this.clusterer = new NgMapMarkerClusterer(gMap, opt_markers, opt_options); } else { this.clusterer = new NgMapMarkerClusterer(gMap); } this.propMapGMarkers = new PropMap(); this.attachEvents(this.opt_events, "opt_events"); this.clusterer.setIgnoreHidden(true); this.noDrawOnSingleAddRemoves = true; $log.info(this); } ClustererMarkerManager.prototype.checkKey = function(gMarker) { var msg; if (gMarker.key == null) { msg = "gMarker.key undefined and it is REQUIRED!!"; return Logger.error(msg); } }; ClustererMarkerManager.prototype.add = function(gMarker) { var exists; this.checkKey(gMarker); exists = this.propMapGMarkers.get(gMarker.key) != null; this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.put(gMarker.key, gMarker); return this.checkSync(); }; ClustererMarkerManager.prototype.addMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; ClustererMarkerManager.prototype.remove = function(gMarker) { var exists; this.checkKey(gMarker); exists = this.propMapGMarkers.get(gMarker.key); if (exists) { this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.remove(gMarker.key); } return this.checkSync(); }; ClustererMarkerManager.prototype.removeMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.remove(gMarker); }; })(this)); }; ClustererMarkerManager.prototype.draw = function() { return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.clear = function() { this.removeMany(this.getGMarkers()); return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) { var eventHandler, eventName, _results; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { _results = []; for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info("" + optionsName + ": Attaching event: " + eventName + " to clusterer"); _results.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName])); } else { _results.push(void 0); } } return _results; } }; ClustererMarkerManager.prototype.clearEvents = function(options) { var eventHandler, eventName, _results; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { _results = []; for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info("" + optionsName + ": Clearing event: " + eventName + " to clusterer"); _results.push(google.maps.event.clearListeners(this.clusterer, eventName)); } else { _results.push(void 0); } } return _results; } }; ClustererMarkerManager.prototype.destroy = function() { this.clearEvents(this.opt_events); this.clearEvents(this.opt_internal_events); return this.clear(); }; ClustererMarkerManager.prototype.fit = function() { return ClustererMarkerManager.__super__.fit.call(this, this.getGMarkers(), this.clusterer.getMap()); }; ClustererMarkerManager.prototype.getGMarkers = function() { return this.clusterer.getMarkers().values(); }; ClustererMarkerManager.prototype.checkSync = function() { if (this.getGMarkers().length !== this.propMapGMarkers.length) { throw "GMarkers out of Sync in MarkerClusterer"; } }; return ClustererMarkerManager; })(FitHelper); return ClustererMarkerManager; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.managers".ns()).factory("MarkerManager".ns(), [ "Logger".ns(), "FitHelper".ns(), "PropMap".ns(), function(Logger, FitHelper, PropMap) { var MarkerManager; MarkerManager = (function(_super) { __extends(MarkerManager, _super); MarkerManager.include(FitHelper); MarkerManager.type = 'MarkerManager'; function MarkerManager(gMap, opt_markers, opt_options) { this.getGMarkers = __bind(this.getGMarkers, this); this.fit = __bind(this.fit, this); this.handleOptDraw = __bind(this.handleOptDraw, this); this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.add = __bind(this.add, this); MarkerManager.__super__.constructor.call(this); this.type = MarkerManager.type; this.gMap = gMap; this.gMarkers = new PropMap(); this.$log = Logger; this.$log.info(this); } MarkerManager.prototype.add = function(gMarker, optDraw) { var exists, msg; if (optDraw == null) { optDraw = true; } if (gMarker.key == null) { msg = "gMarker.key undefined and it is REQUIRED!!"; Logger.error(msg); throw msg; } exists = (this.gMarkers.get(gMarker.key)) != null; if (!exists) { this.handleOptDraw(gMarker, optDraw, true); return this.gMarkers.put(gMarker.key, gMarker); } }; MarkerManager.prototype.addMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; MarkerManager.prototype.remove = function(gMarker, optDraw) { if (optDraw == null) { optDraw = true; } this.handleOptDraw(gMarker, optDraw, false); if (this.gMarkers.get(gMarker.key)) { return this.gMarkers.remove(gMarker.key); } }; MarkerManager.prototype.removeMany = function(gMarkers) { return this.gMarkers.values().forEach((function(_this) { return function(marker) { return _this.remove(marker); }; })(this)); }; MarkerManager.prototype.draw = function() { var deletes; deletes = []; this.gMarkers.values().forEach((function(_this) { return function(gMarker) { if (!gMarker.isDrawn) { if (gMarker.doAdd) { gMarker.setMap(_this.gMap); return gMarker.isDrawn = true; } else { return deletes.push(gMarker); } } }; })(this)); return deletes.forEach((function(_this) { return function(gMarker) { gMarker.isDrawn = false; return _this.remove(gMarker, true); }; })(this)); }; MarkerManager.prototype.clear = function() { this.gMarkers.values().forEach(function(gMarker) { return gMarker.setMap(null); }); delete this.gMarkers; return this.gMarkers = new PropMap(); }; MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) { if (optDraw === true) { if (doAdd) { gMarker.setMap(this.gMap); } else { gMarker.setMap(null); } return gMarker.isDrawn = true; } else { gMarker.isDrawn = false; return gMarker.doAdd = doAdd; } }; MarkerManager.prototype.fit = function() { return MarkerManager.__super__.fit.call(this, this.getGMarkers(), this.gMap); }; MarkerManager.prototype.getGMarkers = function() { return this.gMarkers.values(); }; return MarkerManager; })(FitHelper); return MarkerManager; } ]); }).call(this); (function() { angular.module("google-maps".ns()).factory("add-events".ns(), [ "$timeout", function($timeout) { var addEvent, addEvents; addEvent = function(target, eventName, handler) { return google.maps.event.addListener(target, eventName, function() { handler.apply(this, arguments); return $timeout((function() {}), true); }); }; addEvents = function(target, eventName, handler) { var remove; if (handler) { return addEvent(target, eventName, handler); } remove = []; angular.forEach(eventName, function(_handler, key) { return remove.push(addEvent(target, key, _handler)); }); return function() { angular.forEach(remove, function(listener) { return google.maps.event.removeListener(listener); }); return remove = null; }; }; return addEvents; } ]); }).call(this); (function() { angular.module("google-maps".ns()).factory("array-sync".ns(), [ "add-events".ns(), function(mapEvents) { return function(mapArray, scope, pathEval, pathChangedFn) { var geojsonArray, geojsonHandlers, geojsonWatcher, isSetFromScope, legacyHandlers, legacyWatcher, mapArrayListener, scopePath, watchListener; isSetFromScope = false; scopePath = scope.$eval(pathEval); if (!scope["static"]) { legacyHandlers = { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return scopePath[index] = value; } else { scopePath[index].latitude = value.lat(); return scopePath[index].longitude = value.lng(); } }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return scopePath.splice(index, 0, value); } else { return scopePath.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); } }, remove_at: function(index) { if (isSetFromScope) { return; } return scopePath.splice(index, 1); } }; geojsonArray; if (scopePath.type === "Polygon") { geojsonArray = scopePath.coordinates[0]; } else if (scopePath.type === "LineString") { geojsonArray = scopePath.coordinates; } geojsonHandlers = { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } geojsonArray[index][1] = value.lat(); return geojsonArray[index][0] = value.lng(); }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } return geojsonArray.splice(index, 0, [value.lng(), value.lat()]); }, remove_at: function(index) { if (isSetFromScope) { return; } return geojsonArray.splice(index, 1); } }; mapArrayListener = mapEvents(mapArray, angular.isUndefined(scopePath.type) ? legacyHandlers : geojsonHandlers); } legacyWatcher = function(newPath) { var changed, i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; changed = false; if (newPath) { i = 0; oldLength = oldArray.getLength(); newLength = newPath.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = newPath[i]; if (typeof newValue.equals === "function") { if (!newValue.equals(oldValue)) { oldArray.setAt(i, newValue); changed = true; } } else { if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); changed = true; } } i++; } while (i < newLength) { newValue = newPath[i]; if (typeof newValue.lat === "function" && typeof newValue.lng === "function") { oldArray.push(newValue); } else { oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); } changed = true; i++; } while (i < oldLength) { oldArray.pop(); changed = true; i++; } } isSetFromScope = false; if (changed) { return pathChangedFn(oldArray); } }; geojsonWatcher = function(newPath) { var array, changed, i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; changed = false; if (newPath) { array; if (scopePath.type === "Polygon") { array = newPath.coordinates[0]; } else if (scopePath.type === "LineString") { array = newPath.coordinates; } i = 0; oldLength = oldArray.getLength(); newLength = array.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = array[i]; if ((oldValue.lat() !== newValue[1]) || (oldValue.lng() !== newValue[0])) { oldArray.setAt(i, new google.maps.LatLng(newValue[1], newValue[0])); changed = true; } i++; } while (i < newLength) { newValue = array[i]; oldArray.push(new google.maps.LatLng(newValue[1], newValue[0])); changed = true; i++; } while (i < oldLength) { oldArray.pop(); changed = true; i++; } } isSetFromScope = false; if (changed) { return pathChangedFn(oldArray); } }; watchListener; if (!scope["static"]) { if (angular.isUndefined(scopePath.type)) { watchListener = scope.$watchCollection(pathEval, legacyWatcher); } else { watchListener = scope.$watch(pathEval, geojsonWatcher, true); } } return function() { if (mapArrayListener) { mapArrayListener(); mapArrayListener = null; } if (watchListener) { watchListener(); return watchListener = null; } }; }; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.options.builders".ns()).service("CommonOptionsBuilder".ns(), [ "BaseObject".ns(), "Logger".ns(), function(BaseObject, $log) { var CommonOptionsBuilder; return CommonOptionsBuilder = (function(_super) { __extends(CommonOptionsBuilder, _super); function CommonOptionsBuilder() { this.watchProps = __bind(this.watchProps, this); this.buildOpts = __bind(this.buildOpts, this); return CommonOptionsBuilder.__super__.constructor.apply(this, arguments); } CommonOptionsBuilder.prototype.props = [ 'clickable', 'draggable', 'editable', 'visible', { prop: 'stroke', isColl: true } ]; CommonOptionsBuilder.prototype.buildOpts = function(customOpts, forEachOpts) { var hasModel, model, opts, _ref, _ref1, _ref2; if (customOpts == null) { customOpts = {}; } if (forEachOpts == null) { forEachOpts = {}; } if (!this.scope) { $log.error("this.scope not defined in CommonOptionsBuilder can not buildOpts"); return; } if (!this.map) { $log.error("this.map not defined in CommonOptionsBuilder can not buildOpts"); return; } hasModel = _(this.scope).chain().keys().contains('model').value(); model = hasModel ? this.scope.model : this.scope; opts = angular.extend(customOpts, this.DEFAULTS, { map: this.map, strokeColor: (_ref = model.stroke) != null ? _ref.color : void 0, strokeOpacity: (_ref1 = model.stroke) != null ? _ref1.opacity : void 0, strokeWeight: (_ref2 = model.stroke) != null ? _ref2.weight : void 0 }); angular.forEach(angular.extend(forEachOpts, { clickable: true, draggable: false, editable: false, "static": false, fit: false, visible: true, zIndex: 0 }), (function(_this) { return function(defaultValue, key) { if (angular.isUndefined(model[key] || model[key] === null)) { return opts[key] = defaultValue; } else { return opts[key] = model[key]; } }; })(this)); if (opts["static"]) { opts.editable = false; } return opts; }; CommonOptionsBuilder.prototype.watchProps = function(props) { if (props == null) { props = this.props; } return props.forEach((function(_this) { return function(prop) { if ((_this.attrs[prop] != null) || (_this.attrs[prop != null ? prop.prop : void 0] != null)) { if (prop != null ? prop.isColl : void 0) { return _this.scope.$watchCollection(prop.prop, _this.setMyOptions); } else { return _this.scope.$watch(prop, _this.setMyOptions); } } }; })(this)); }; return CommonOptionsBuilder; })(BaseObject); } ]); }).call(this); (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.options.builders".ns()).factory("PolylineOptionsBuilder".ns(), [ "CommonOptionsBuilder".ns(), function(CommonOptionsBuilder) { var PolylineOptionsBuilder; return PolylineOptionsBuilder = (function(_super) { __extends(PolylineOptionsBuilder, _super); function PolylineOptionsBuilder() { return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments); } PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints) { return PolylineOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, { geodesic: false }); }; return PolylineOptionsBuilder; })(CommonOptionsBuilder); } ]).factory("ShapeOptionsBuilder".ns(), [ "CommonOptionsBuilder".ns(), function(CommonOptionsBuilder) { var ShapeOptionsBuilder; return ShapeOptionsBuilder = (function(_super) { __extends(ShapeOptionsBuilder, _super); function ShapeOptionsBuilder() { return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments); } ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, forEachOpts) { var _ref, _ref1; customOpts = angular.extend(customOpts, { fillColor: (_ref = this.scope.fill) != null ? _ref.color : void 0, fillOpacity: (_ref1 = this.scope.fill) != null ? _ref1.opacity : void 0 }); return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, forEachOpts); }; return ShapeOptionsBuilder; })(CommonOptionsBuilder); } ]).factory("PolygonOptionsBuilder".ns(), [ "ShapeOptionsBuilder".ns(), function(ShapeOptionsBuilder) { var PolygonOptionsBuilder; return PolygonOptionsBuilder = (function(_super) { __extends(PolygonOptionsBuilder, _super); function PolygonOptionsBuilder() { return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments); } PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints) { return PolygonOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, { geodesic: false }); }; return PolygonOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory("RectangleOptionsBuilder".ns(), [ "ShapeOptionsBuilder".ns(), function(ShapeOptionsBuilder) { var RectangleOptionsBuilder; return RectangleOptionsBuilder = (function(_super) { __extends(RectangleOptionsBuilder, _super); function RectangleOptionsBuilder() { return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments); } RectangleOptionsBuilder.prototype.buildOpts = function(bounds) { return RectangleOptionsBuilder.__super__.buildOpts.call(this, { bounds: bounds }); }; return RectangleOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory("CircleOptionsBuilder".ns(), [ "ShapeOptionsBuilder".ns(), function(ShapeOptionsBuilder) { var CircleOptionsBuilder; return CircleOptionsBuilder = (function(_super) { __extends(CircleOptionsBuilder, _super); function CircleOptionsBuilder() { return CircleOptionsBuilder.__super__.constructor.apply(this, arguments); } CircleOptionsBuilder.prototype.buildOpts = function(center, radius) { return CircleOptionsBuilder.__super__.buildOpts.call(this, { center: center, radius: radius }); }; return CircleOptionsBuilder; })(ShapeOptionsBuilder); } ]); }).call(this); (function() { angular.module("google-maps.directives.api.options".ns()).service("MarkerOptions".ns(), [ "Logger".ns(), "GmapUtil".ns(), function($log, GmapUtil) { return _.extend(GmapUtil, { createOptions: function(coords, icon, defaults, map) { var opts; if (map == null) { map = void 0; } if (defaults == null) { defaults = {}; } opts = angular.extend({}, defaults, { position: defaults.position != null ? defaults.position : GmapUtil.getCoords(coords), visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords) }); if ((defaults.icon != null) || (icon != null)) { opts = angular.extend(opts, { icon: defaults.icon != null ? defaults.icon : icon }); } if (map != null) { opts.map = map; } return opts; }, isLabel: function(options) { if ((options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null)) { return true; } else { return false; } } }); } ]); }).call(this); /* angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicholas McCready - https://twitter.com/nmccready Original idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , & http://jsfiddle.net/YsQdh/88/ */ (function() { angular.module("google-maps.directives.api.models.child".ns()).factory("DrawFreeHandChildModel".ns(), [ "Logger".ns(), '$q', function($log, $q) { var drawFreeHand, freeHandMgr; drawFreeHand = function(map, polys, enable) { var move, poly; this.polys = polys; poly = new google.maps.Polyline({ map: map, clickable: false }); move = google.maps.event.addListener(map, 'mousemove', function(e) { return poly.getPath().push(e.latLng); }); google.maps.event.addListenerOnce(map, 'mouseup', function(e) { var path; google.maps.event.removeListener(move); path = poly.getPath(); poly.setMap(null); polys.push(new google.maps.Polygon({ map: map, path: path })); poly = null; google.maps.event.clearListeners(map.getDiv(), 'mousedown'); return enable(); }); return void 0; }; freeHandMgr = function(map) { var disableMap, enable; this.map = map; enable = (function(_this) { return function() { var _ref; if ((_ref = _this.deferred) != null) { _ref.resolve(); } return _this.map.setOptions(_this.oldOptions); }; })(this); disableMap = (function(_this) { return function() { $log.info('disabling map move'); _this.oldOptions = map.getOptions(); return _this.map.setOptions({ draggable: false, zoomControl: false, scrollwheel: false, disableDoubleClickZoom: false }); }; })(this); this.engage = (function(_this) { return function(polys) { _this.polys = polys; _this.deferred = $q.defer(); disableMap(); $log.info('DrawFreeHandChildModel is engaged (drawing).'); google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) { return drawFreeHand(_this.map, _this.polys, enable); }); return _this.deferred.promise; }; })(this); return this; }; return freeHandMgr; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.models.child".ns()).factory("MarkerChildModel".ns(), [ "ModelKey".ns(), "GmapUtil".ns(), "Logger".ns(), "EventsHelper".ns(), "PropertyAction".ns(), "MarkerOptions".ns(), "IMarker".ns(), "MarkerManager".ns(), "uiGmapPromise", function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) { var MarkerChildModel, keys; keys = ['coords', 'icon', 'options', 'fit']; MarkerChildModel = (function(_super) { var destroy; __extends(MarkerChildModel, _super); MarkerChildModel.include(GmapUtil); MarkerChildModel.include(EventsHelper); MarkerChildModel.include(MarkerOptions); destroy = function(child) { if ((child != null ? child.gMarker : void 0) != null) { child.removeEvents(child.externalListeners); child.removeEvents(child.internalListeners); if (child != null ? child.gMarker : void 0) { if (child.removeFromManager) { child.gMarkerManager.remove(child.gMarker); } child.gMarker.setMap(null); return child.gMarker = null; } } }; function MarkerChildModel(scope, model, keys, gMap, defaults, doClick, gMarkerManager, doDrawSelf, trackModel, needRedraw) { var action, firstTime; this.model = model; this.keys = keys; this.gMap = gMap; this.defaults = defaults; this.doClick = doClick; this.gMarkerManager = gMarkerManager; this.doDrawSelf = doDrawSelf != null ? doDrawSelf : true; this.trackModel = trackModel != null ? trackModel : true; this.needRedraw = needRedraw != null ? needRedraw : false; this.internalEvents = __bind(this.internalEvents, this); this.setLabelOptions = __bind(this.setLabelOptions, this); this.setOptions = __bind(this.setOptions, this); this.setIcon = __bind(this.setIcon, this); this.setCoords = __bind(this.setCoords, this); this.isNotValid = __bind(this.isNotValid, this); this.maybeSetScopeValue = __bind(this.maybeSetScopeValue, this); this.createMarker = __bind(this.createMarker, this); this.setMyScope = __bind(this.setMyScope, this); this.destroy = __bind(this.destroy, this); this.deferred = uiGmapPromise.defer(); _.each(this.keys, (function(_this) { return function(v, k) { return _this[k + 'Key'] = _.isFunction(_this.keys[k]) ? _this.keys[k]() : _this.keys[k]; }; })(this)); this.idKey = this.idKeyKey || "id"; if (this.model[this.idKey] != null) { this.id = this.model[this.idKey]; } MarkerChildModel.__super__.constructor.call(this, scope); this.setMyScope('all', this.model, void 0, true); this.scope.getGMarker = (function(_this) { return function() { return _this.gMarker; }; })(this); this.createMarker(this.model); firstTime = true; if (this.trackModel) { this.scope.model = this.model; this.scope.$watch('model', (function(_this) { return function(newValue, oldValue) { var changes; if (newValue !== oldValue) { changes = _this.getChanges(newValue, oldValue, IMarker.keys); return _.each(changes, function(v, k) { _this.setMyScope(k, newValue, oldValue); return _this.needRedraw = true; }); } }; })(this), true); } else { action = new PropertyAction((function(_this) { return function(calledKey, newVal) { return _this.setMyScope(calledKey, scope); }; })(this), false); _.each(this.keys, function(v, k) { return scope.$watch(k, action.sic, true); }); } this.scope.$on("$destroy", (function(_this) { return function() { return destroy(_this); }; })(this)); $log.info(this); } MarkerChildModel.prototype.destroy = function(removeFromManager) { if (removeFromManager == null) { removeFromManager = true; } this.removeFromManager = removeFromManager; return this.scope.$destroy(); }; MarkerChildModel.prototype.setMyScope = function(thingThatChanged, model, oldModel, isInit) { var justCreated; if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } if (model == null) { model = this.model; } if (!this.gMarker) { this.setOptions(this.scope); justCreated = true; } switch (thingThatChanged) { case 'all': return _.each(this.keys, (function(_this) { return function(v, k) { return _this.setMyScope(k, model, oldModel, isInit); }; })(this)); case 'icon': return this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon); case 'coords': return this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords); case 'options': if (!justCreated) { return this.createMarker(model, oldModel, isInit); } } }; MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit) { if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } return this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, this.evalModelHandle, isInit, this.setOptions); }; MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter) { var newValue, oldVal; if (gSetter == null) { gSetter = void 0; } if (oldModel === void 0) { this.scope[scopePropName] = evaluate(model, modelKey); if (gSetter != null) { gSetter(this.scope); } return; } oldVal = evaluate(oldModel, modelKey); newValue = evaluate(model, modelKey); if (newValue !== oldVal) { this.scope[scopePropName] = newValue; if (!isInit) { if (gSetter != null) { gSetter(this.scope); } if (this.doDrawSelf) { return this.gMarkerManager.draw(); } } } }; MarkerChildModel.prototype.isNotValid = function(scope, doCheckGmarker) { var hasIdenticalScopes, hasNoGmarker; if (doCheckGmarker == null) { doCheckGmarker = true; } hasNoGmarker = !doCheckGmarker ? false : this.gMarker === void 0; hasIdenticalScopes = !this.trackModel ? scope.$id !== this.scope.$id : false; return hasIdenticalScopes || hasNoGmarker; }; MarkerChildModel.prototype.setCoords = function(scope) { if (this.isNotValid(scope) || (this.gMarker == null)) { return; } if (this.getProp(this.coordsKey, this.model) != null) { if (!this.validateCoords(this.getProp(this.coordsKey, this.model))) { $log.debug("MarkerChild does not have coords yet. They may be defined later."); return; } this.gMarker.setPosition(this.getCoords(this.getProp(this.coordsKey, this.model))); this.gMarker.setVisible(this.validateCoords(this.getProp(this.coordsKey, this.model))); return this.gMarkerManager.add(this.gMarker); } else { return this.gMarkerManager.remove(this.gMarker); } }; MarkerChildModel.prototype.setIcon = function(scope) { if (this.isNotValid(scope) || (this.gMarker == null)) { return; } this.gMarker.setIcon(this.getProp(this.iconKey, this.model)); this.gMarkerManager.add(this.gMarker); this.gMarker.setPosition(this.getCoords(this.getProp(this.coordsKey, this.model))); return this.gMarker.setVisible(this.validateCoords(this.getProp(this.coordsKey, this.model))); }; MarkerChildModel.prototype.setOptions = function(scope) { var coords, icon, _options; if (this.isNotValid(scope, false)) { return; } if (scope.coords == null) { return; } coords = this.getProp(this.coordsKey, this.model); icon = this.getProp(this.iconKey, this.model); _options = this.getProp(this.optionsKey, this.model); this.opts = this.createOptions(coords, icon, _options); if ((this.gMarker != null) && (this.isLabel(this.gMarker === this.isLabel(this.opts)))) { this.gMarker.setOptions(this.opts); } else { if (this.gMarker != null) { this.gMarkerManager.remove(this.gMarker); this.gMarker = null; } } if (!this.gMarker) { if (this.isLabel(this.opts)) { this.gMarker = new MarkerWithLabel(this.setLabelOptions(this.opts)); } else { this.gMarker = new google.maps.Marker(this.opts); } } if (this.externalListeners) { this.removeEvents(this.externalListeners); } if (this.internalListeners) { this.removeEvents(this.internalListeners); } this.externalListeners = this.setEvents(this.gMarker, this.scope, this.model, ['dragend']); this.internalListeners = this.setEvents(this.gMarker, { events: this.internalEvents(), $evalAsync: function() {} }, this.model); if (this.id != null) { this.gMarker.key = this.id; } this.gMarkerManager.add(this.gMarker); if (this.gMarker && (this.gMarker.getMap() || this.gMarkerManager.type !== MarkerManager.type)) { this.deferred.resolve(this.gMarker); } else { if (!this.gMarker) { this.deferred.reject("gMarker is null"); } if (!(this.gMarker.getMap() && this.gMarkerManager.type === MarkerManager.type)) { $log.warn('gMarker has no map yet'); this.deferred.resolve(this.gMarker); } } if (this.model[this.fitKey]) { return this.gMarkerManager.fit(); } }; MarkerChildModel.prototype.setLabelOptions = function(opts) { opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor); return opts; }; MarkerChildModel.prototype.internalEvents = function() { return { dragend: (function(_this) { return function(marker, eventName, model, mousearg) { var events, modelToSet, newCoords; modelToSet = _this.trackModel ? _this.scope.model : _this.model; newCoords = _this.setCoordsFromEvent(_this.modelOrKey(modelToSet, _this.coordsKey), _this.gMarker.getPosition()); modelToSet = _this.setVal(model, _this.coordsKey, newCoords); events = _this.scope.events; if ((events != null ? events.dragend : void 0) != null) { events.dragend(marker, eventName, modelToSet, mousearg); } return _this.scope.$apply(); }; })(this), click: (function(_this) { return function(marker, eventName, model, mousearg) { var click; click = _.isFunction(_this.clickKey) ? _this.clickKey : _this.getProp(_this.clickKey, _this.model); if (_this.doClick && (click != null)) { return _this.scope.$evalAsync(click(marker, eventName, _this.model, mousearg)); } }; })(this) }; }; return MarkerChildModel; })(ModelKey); return MarkerChildModel; } ]); }).call(this); (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api".ns()).factory("PolygonChildModel".ns(), [ "PolygonOptionsBuilder".ns(), "Logger".ns(), "$timeout", "array-sync".ns(), "GmapUtil".ns(), "EventsHelper".ns(), function(Builder, $log, $timeout, arraySync, GmapUtil, EventsHelper) { var PolygonChildModel; return PolygonChildModel = (function(_super) { __extends(PolygonChildModel, _super); PolygonChildModel.include(GmapUtil); PolygonChildModel.include(EventsHelper); function PolygonChildModel(scope, attrs, map, defaults, model) { var arraySyncer, pathPoints, polygon; this.scope = scope; this.attrs = attrs; this.map = map; this.defaults = defaults; this.model = model; this.listeners = void 0; if (angular.isUndefined(scope.path) || scope.path === null || !this.validatePath(scope.path)) { $log.error("polygon: no valid path attribute found"); return; } pathPoints = this.convertPathPoints(scope.path); polygon = new google.maps.Polygon(this.buildOpts(pathPoints)); if (scope.fit) { this.extendMapBounds(this.map, pathPoints); } if (!scope["static"] && angular.isDefined(scope.editable)) { scope.$watch("editable", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setEditable(newValue); } }); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setDraggable(newValue); } }); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setVisible(newValue); } }); } if (angular.isDefined(scope.geodesic)) { scope.$watch("geodesic", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.opacity)) { scope.$watch("stroke.opacity", (function(_this) { return function(newValue, oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) { scope.$watch("stroke.weight", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) { scope.$watch("stroke.color", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.color)) { scope.$watch("fill.color", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.opacity)) { scope.$watch("fill.opacity", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.zIndex)) { scope.$watch("zIndex", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) { this.listeners = EventsHelper.setEvents(polygon, scope, scope); } arraySyncer = arraySync(polygon.getPath(), scope, "path", (function(_this) { return function(pathPoints) { if (scope.fit) { return _this.extendMapBounds(_this.map, pathPoints); } }; })(this)); scope.$on("$destroy", (function(_this) { return function() { polygon.setMap(null); _this.removeEvents(_this.listeners); if (arraySyncer) { arraySyncer(); return arraySyncer = null; } }; })(this)); } return PolygonChildModel; })(Builder); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api".ns()).factory("PolylineChildModel".ns(), [ "PolylineOptionsBuilder".ns(), "Logger".ns(), "$timeout", "array-sync".ns(), "GmapUtil".ns(), "EventsHelper".ns(), function(Builder, $log, $timeout, arraySync, GmapUtil, EventsHelper) { var PolylineChildModel; return PolylineChildModel = (function(_super) { __extends(PolylineChildModel, _super); PolylineChildModel.include(GmapUtil); PolylineChildModel.include(EventsHelper); function PolylineChildModel(scope, attrs, map, defaults, model) { var createPolyline; this.scope = scope; this.attrs = attrs; this.map = map; this.defaults = defaults; this.model = model; this.clean = __bind(this.clean, this); createPolyline = (function(_this) { return function() { var pathPoints; pathPoints = _this.convertPathPoints(_this.scope.path); if (_this.polyline != null) { _this.clean(); } if (pathPoints.length > 0) { _this.polyline = new google.maps.Polyline(_this.buildOpts(pathPoints)); } if (_this.polyline) { if (_this.scope.fit) { _this.extendMapBounds(map, pathPoints); } arraySync(_this.polyline.getPath(), _this.scope, "path", function(pathPoints) { if (_this.scope.fit) { return _this.extendMapBounds(map, pathPoints); } }); return _this.listeners = _this.model ? _this.setEvents(_this.polyline, _this.scope, _this.model) : _this.setEvents(_this.polyline, _this.scope, _this.scope); } }; })(this); createPolyline(); scope.$watch('path', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue) || !_this.polyline) { return createPolyline(); } }; })(this)); if (!scope["static"] && angular.isDefined(scope.editable)) { scope.$watch("editable", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setEditable(newValue) : void 0; } }; })(this)); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setDraggable(newValue) : void 0; } }; })(this)); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setVisible(newValue) : void 0; } }; })(this)); } if (angular.isDefined(scope.geodesic)) { scope.$watch("geodesic", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) { scope.$watch("stroke.weight", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) { scope.$watch("stroke.color", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.opacity)) { scope.$watch("stroke.opacity", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }; })(this)); } if (angular.isDefined(scope.icons)) { scope.$watch("icons", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }; })(this)); } scope.$on("$destroy", (function(_this) { return function() { _this.clean(); return _this.scope = null; }; })(this)); $log.info(this); } PolylineChildModel.prototype.clean = function() { var arraySyncer, _ref; this.removeEvents(this.listeners); if ((_ref = this.polyline) != null) { _ref.setMap(null); } this.polyline = null; if (arraySyncer) { arraySyncer(); return arraySyncer = null; } }; PolylineChildModel.prototype.destroy = function() { return this.scope.$destroy(); }; return PolylineChildModel; })(Builder); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.models.child".ns()).factory("WindowChildModel".ns(), [ "BaseObject".ns(), "GmapUtil".ns(), "Logger".ns(), "$compile", "$http", "$templateCache", function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache) { var WindowChildModel; WindowChildModel = (function(_super) { __extends(WindowChildModel, _super); WindowChildModel.include(GmapUtil); function WindowChildModel(model, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element, needToManualDestroy, markerIsVisibleAfterWindowClose) { this.model = model; this.scope = scope; this.opts = opts; this.isIconVisibleOnClick = isIconVisibleOnClick; this.mapCtrl = mapCtrl; this.markerScope = markerScope; this.element = element; this.needToManualDestroy = needToManualDestroy != null ? needToManualDestroy : false; this.markerIsVisibleAfterWindowClose = markerIsVisibleAfterWindowClose != null ? markerIsVisibleAfterWindowClose : true; this.destroy = __bind(this.destroy, this); this.remove = __bind(this.remove, this); this.getLatestPosition = __bind(this.getLatestPosition, this); this.hideWindow = __bind(this.hideWindow, this); this.showWindow = __bind(this.showWindow, this); this.handleClick = __bind(this.handleClick, this); this.watchOptions = __bind(this.watchOptions, this); this.watchCoords = __bind(this.watchCoords, this); this.createGWin = __bind(this.createGWin, this); this.watchElement = __bind(this.watchElement, this); this.watchAndDoShow = __bind(this.watchAndDoShow, this); this.doShow = __bind(this.doShow, this); this.getGmarker = function() { var _ref, _ref1; if (((_ref = this.markerScope) != null ? _ref['getGMarker'] : void 0) != null) { return (_ref1 = this.markerScope) != null ? _ref1.getGMarker() : void 0; } }; this.googleMapsHandles = []; this.createGWin(); if (this.getGmarker() != null) { this.getGmarker().setClickable(true); } this.watchElement(); this.watchOptions(); this.watchCoords(); this.watchAndDoShow(); this.scope.$on("$destroy", (function(_this) { return function() { return _this.destroy(); }; })(this)); $log.info(this); } WindowChildModel.prototype.doShow = function() { if (this.scope.show) { return this.showWindow(); } else { return this.hideWindow(); } }; WindowChildModel.prototype.watchAndDoShow = function() { if (this.model.show != null) { this.scope.show = this.model.show; } this.scope.$watch('show', this.doShow, true); return this.doShow(); }; WindowChildModel.prototype.watchElement = function() { return this.scope.$watch((function(_this) { return function() { var _ref; if (!(_this.element || _this.html)) { return; } if (_this.html !== _this.element.html() && _this.gWin) { if ((_ref = _this.opts) != null) { _ref.content = void 0; } _this.remove(); return _this.createGWin(); } }; })(this)); }; WindowChildModel.prototype.createGWin = function() { var defaults, _opts, _ref, _ref1; if (this.gWin == null) { defaults = {}; if (this.opts != null) { if (this.scope.coords) { this.opts.position = this.getCoords(this.scope.coords); } defaults = this.opts; } if (this.element) { this.html = _.isObject(this.element) ? this.element.html() : this.element; } _opts = this.scope.options ? this.scope.options : defaults; this.opts = this.createWindowOptions(this.getGmarker(), this.markerScope || this.scope, this.html, _opts); } if ((this.opts != null) && !this.gWin) { if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) { this.gWin = new window.InfoBox(this.opts); } else { this.gWin = new google.maps.InfoWindow(this.opts); } this.handleClick((_ref = this.scope) != null ? (_ref1 = _ref.options) != null ? _ref1.forceClick : void 0 : void 0); this.doShow(); return this.googleMapsHandles.push(google.maps.event.addListener(this.gWin, 'closeclick', (function(_this) { return function() { if (_this.getGmarker()) { _this.getGmarker().setAnimation(_this.oldMarkerAnimation); if (_this.markerIsVisibleAfterWindowClose) { _.delay(function() { _this.getGmarker().setVisible(false); return _this.getGmarker().setVisible(_this.markerIsVisibleAfterWindowClose); }, 250); } } _this.gWin.isOpen(false); _this.model.show = false; if (_this.scope.closeClick != null) { return _this.scope.$apply(_this.scope.closeClick()); } else { return _this.scope.$apply(); } }; })(this))); } }; WindowChildModel.prototype.watchCoords = function() { var scope; scope = this.markerScope != null ? this.markerScope : this.scope; return scope.$watch('coords', (function(_this) { return function(newValue, oldValue) { var pos; if (newValue !== oldValue) { if (newValue == null) { _this.hideWindow(); } else if (!_this.validateCoords(newValue)) { $log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model))); return; } pos = _this.getCoords(newValue); _this.gWin.setPosition(pos); if (_this.opts) { return _this.opts.position = pos; } } }; })(this), true); }; WindowChildModel.prototype.watchOptions = function() { return this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.opts = newValue; if (_this.gWin != null) { _this.gWin.setOptions(_this.opts); if ((_this.opts.visible != null) && _this.opts.visible) { return _this.showWindow(); } else if (_this.opts.visible != null) { return _this.hideWindow(); } } } }; })(this), true); }; WindowChildModel.prototype.handleClick = function(forceClick) { var click; if (this.gWin == null) { return; } click = (function(_this) { return function() { var pos, _ref, _ref1; if (_this.gWin == null) { _this.createGWin(); } pos = _this.scope.coords != null ? (_ref = _this.gWin) != null ? _ref.getPosition() : void 0 : (_ref1 = _this.getGmarker()) != null ? _ref1.getPosition() : void 0; if (!pos) { return; } if (_this.gWin != null) { _this.gWin.setPosition(pos); if (_this.opts) { _this.opts.position = pos; } _this.showWindow(); } if (_this.getGmarker() != null) { _this.initialMarkerVisibility = _this.getGmarker().getVisible(); _this.oldMarkerAnimation = _this.getGmarker().getAnimation(); return _this.getGmarker().setVisible(_this.isIconVisibleOnClick); } }; })(this); if (forceClick) { click(); } if (this.getGmarker()) { return this.googleMapsHandles.push(google.maps.event.addListener(this.getGmarker(), 'click', click)); } }; WindowChildModel.prototype.showWindow = function() { var compiled, templateScope; if (this.gWin != null) { if (this.scope.templateUrl) { $http.get(this.scope.templateUrl, { cache: $templateCache }).then((function(_this) { return function(content) { var compiled, templateScope; templateScope = _this.scope.$new(); if (angular.isDefined(_this.scope.templateParameter)) { templateScope.parameter = _this.scope.templateParameter; } compiled = $compile(content.data)(templateScope); return _this.gWin.setContent(compiled[0]); }; })(this)); } else if (this.scope.template) { templateScope = this.scope.$new(); if (angular.isDefined(this.scope.templateParameter)) { templateScope.parameter = this.scope.templateParameter; } compiled = $compile(this.scope.template)(templateScope); this.gWin.setContent(compiled[0]); } if (!this.gWin.isOpen()) { this.gWin.open(this.mapCtrl, this.getGmarker() ? this.getGmarker() : void 0); return this.model.show = this.gWin.isOpen(); } } }; WindowChildModel.prototype.hideWindow = function() { if ((this.gWin != null) && this.gWin.isOpen()) { return this.gWin.close(); } }; WindowChildModel.prototype.getLatestPosition = function(overridePos) { if ((this.gWin != null) && (this.getGmarker() != null) && !overridePos) { return this.gWin.setPosition(this.getGmarker().getPosition()); } else { if (overridePos) { return this.gWin.setPosition(overridePos); } } }; WindowChildModel.prototype.remove = function() { this.hideWindow(); _.each(this.googleMapsHandles, function(h) { return google.maps.event.removeListener(h); }); this.googleMapsHandles.length = 0; delete this.gWin; return delete this.opts; }; WindowChildModel.prototype.destroy = function(manualOverride) { var self, _ref; if (manualOverride == null) { manualOverride = false; } this.remove(); if ((this.scope != null) && ((_ref = this.scope) != null ? _ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) { this.scope.$destroy(); } return self = void 0; }; return WindowChildModel; })(BaseObject); return WindowChildModel; } ]); }).call(this); (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.models.parent".ns()).factory("CircleParentModel".ns(), [ 'Logger'.ns(), '$timeout', "GmapUtil".ns(), "EventsHelper".ns(), "CircleOptionsBuilder".ns(), function($log, $timeout, GmapUtil, EventsHelper, Builder) { var CircleParentModel; return CircleParentModel = (function(_super) { __extends(CircleParentModel, _super); CircleParentModel.include(GmapUtil); CircleParentModel.include(EventsHelper); function CircleParentModel(scope, element, attrs, map, DEFAULTS) { var circle, listeners; this.scope = scope; this.attrs = attrs; this.map = map; this.DEFAULTS = DEFAULTS; circle = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.isEqual(newVals, oldVals)) { return circle.setOptions(_this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); } }; })(this); this.props = this.props.concat([ { prop: 'center', isColl: true }, { prop: 'fill', isColl: true }, 'radius' ]); this.watchProps(); listeners = this.setEvents(circle, scope, scope); google.maps.event.addListener(circle, 'radius_changed', function() { return scope.$evalAsync(function() { return scope.radius = circle.getRadius(); }); }); google.maps.event.addListener(circle, 'center_changed', function() { return scope.$evalAsync(function() { if (angular.isDefined(scope.center.type)) { scope.center.coordinates[1] = circle.getCenter().lat(); return scope.center.coordinates[0] = circle.getCenter().lng(); } else { scope.center.latitude = circle.getCenter().lat(); return scope.center.longitude = circle.getCenter().lng(); } }); }); scope.$on("$destroy", (function(_this) { return function() { _this.removeEvents(listeners); return circle.setMap(null); }; })(this)); $log.info(this); } return CircleParentModel; })(Builder); } ]); }).call(this); (function() { angular.module("google-maps.directives.api.models.parent".ns()).factory("DrawingManagerParentModel".ns(), [ 'Logger'.ns(), '$timeout', function($log, $timeout) { var DrawingManagerParentModel; return DrawingManagerParentModel = (function() { function DrawingManagerParentModel(scope, element, attrs, map) { var drawingManager; this.scope = scope; this.attrs = attrs; this.map = map; drawingManager = new google.maps.drawing.DrawingManager(this.scope.options); drawingManager.setMap(this.map); if (this.scope.control != null) { this.scope.control.getDrawingManager = (function(_this) { return function() { return drawingManager; }; })(this); } if (!this.scope["static"] && this.scope.options) { this.scope.$watch("options", (function(_this) { return function(newValue) { return drawingManager != null ? drawingManager.setOptions(newValue) : void 0; }; })(this), true); } scope.$on("$destroy", (function(_this) { return function() { drawingManager.setMap(null); return drawingManager = null; }; })(this)); } return DrawingManagerParentModel; })(); } ]); }).call(this); /* - interface for all markers to derrive from - to enforce a minimum set of requirements - attributes - coords - icon - implementation needed on watches */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIMarkerParentModel", [ "uiGmapModelKey", "uiGmapLogger", function(ModelKey, Logger) { var IMarkerParentModel; IMarkerParentModel = (function(_super) { __extends(IMarkerParentModel, _super); IMarkerParentModel.prototype.DEFAULTS = {}; function IMarkerParentModel(scope, element, attrs, map) { this.scope = scope; this.element = element; this.attrs = attrs; this.map = map; this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.watch = __bind(this.watch, this); this.validateScope = __bind(this.validateScope, this); IMarkerParentModel.__super__.constructor.call(this, this.scope); this.$log = Logger; if (!this.validateScope(scope)) { throw new String("Unable to construct IMarkerParentModel due to invalid scope"); } this.doClick = angular.isDefined(attrs.click); if (scope.options != null) { this.DEFAULTS = scope.options; } this.watch('coords', this.scope); this.watch('icon', this.scope); this.watch('options', this.scope); scope.$on("$destroy", (function(_this) { return function() { return _this.onDestroy(scope); }; })(this)); } IMarkerParentModel.prototype.validateScope = function(scope) { var ret; if (scope == null) { this.$log.error(this.constructor.name + ": invalid scope used"); return false; } ret = scope.coords != null; if (!ret) { this.$log.error(this.constructor.name + ": no valid coords attribute found"); return false; } return ret; }; IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) { if (equalityCheck == null) { equalityCheck = true; } return scope.$watch(propNameToWatch, (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.onWatch(propNameToWatch, scope, newValue, oldValue); } }; })(this), equalityCheck); }; IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {}; IMarkerParentModel.prototype.onDestroy = function(scope) { throw new String("OnDestroy Not Implemented!!"); }; return IMarkerParentModel; })(ModelKey); return IMarkerParentModel; } ]); }).call(this); /* - interface directive for all window(s) to derrive from */ (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.models.parent".ns()).factory("IWindowParentModel".ns(), [ "ModelKey".ns(), "GmapUtil".ns(), "Logger".ns(), function(ModelKey, GmapUtil, Logger) { var IWindowParentModel; IWindowParentModel = (function(_super) { __extends(IWindowParentModel, _super); IWindowParentModel.include(GmapUtil); function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) { IWindowParentModel.__super__.constructor.call(this, scope); this.$log = Logger; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; this.DEFAULTS = {}; if (scope.options != null) { this.DEFAULTS = scope.options; } } return IWindowParentModel; })(ModelKey); return IWindowParentModel; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.models.parent".ns()).factory("LayerParentModel".ns(), [ "BaseObject".ns(), "Logger".ns(), '$timeout', function(BaseObject, Logger, $timeout) { var LayerParentModel; LayerParentModel = (function(_super) { __extends(LayerParentModel, _super); function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) { this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0; this.$log = $log != null ? $log : Logger; this.createGoogleLayer = __bind(this.createGoogleLayer, this); if (this.attrs.type == null) { this.$log.info("type attribute for the layer directive is mandatory. Layer creation aborted!!"); return; } this.createGoogleLayer(); this.doShow = true; if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.layer.setMap(this.gMap); } this.scope.$watch("show", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.layer.setMap(_this.gMap); } else { return _this.layer.setMap(null); } } }; })(this), true); this.scope.$watch("options", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.layer.setMap(null); _this.layer = null; return _this.createGoogleLayer(); } }; })(this), true); this.scope.$on("$destroy", (function(_this) { return function() { return _this.layer.setMap(null); }; })(this)); } LayerParentModel.prototype.createGoogleLayer = function() { var fn; if (this.attrs.options == null) { this.layer = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type](); } else { this.layer = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options); } if ((this.layer != null) && (this.onLayerCreated != null)) { fn = this.onLayerCreated(this.scope, this.layer); if (fn) { return fn(this.layer); } } }; return LayerParentModel; })(BaseObject); return LayerParentModel; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.models.parent".ns()).factory("MapTypeParentModel".ns(), [ "BaseObject".ns(), "Logger".ns(), '$timeout', function(BaseObject, Logger, $timeout) { var MapTypeParentModel; MapTypeParentModel = (function(_super) { __extends(MapTypeParentModel, _super); function MapTypeParentModel(scope, element, attrs, gMap, $log) { this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.$log = $log != null ? $log : Logger; this.hideOverlay = __bind(this.hideOverlay, this); this.showOverlay = __bind(this.showOverlay, this); this.refreshMapType = __bind(this.refreshMapType, this); this.createMapType = __bind(this.createMapType, this); if (this.attrs.options == null) { this.$log.info("options attribute for the map-type directive is mandatory. Map type creation aborted!!"); return; } this.id = this.gMap.overlayMapTypesCount = this.gMap.overlayMapTypesCount + 1 || 0; this.doShow = true; this.createMapType(); if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.showOverlay(); } this.scope.$watch("show", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.showOverlay(); } else { return _this.hideOverlay(); } } }; })(this), true); this.scope.$watch("options", (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.refreshMapType(); } }; })(this), true); if (angular.isDefined(this.attrs.refresh)) { this.scope.$watch("refresh", (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.refreshMapType(); } }; })(this), true); } this.scope.$on("$destroy", (function(_this) { return function() { _this.hideOverlay(); return _this.mapType = null; }; })(this)); } MapTypeParentModel.prototype.createMapType = function() { if (this.scope.options.getTile != null) { this.mapType = this.scope.options; } else if (this.scope.options.getTileUrl != null) { this.mapType = new google.maps.ImageMapType(this.scope.options); } else { this.$log.info("options should provide either getTile or getTileUrl methods. Map type creation aborted!!"); return; } if (this.attrs.id && this.scope.id) { this.gMap.mapTypes.set(this.scope.id, this.mapType); if (!angular.isDefined(this.attrs.show)) { this.doShow = false; } } return this.mapType.layerId = this.id; }; MapTypeParentModel.prototype.refreshMapType = function() { this.hideOverlay(); this.mapType = null; this.createMapType(); if (this.doShow && (this.gMap != null)) { return this.showOverlay(); } }; MapTypeParentModel.prototype.showOverlay = function() { return this.gMap.overlayMapTypes.push(this.mapType); }; MapTypeParentModel.prototype.hideOverlay = function() { var found; found = false; return this.gMap.overlayMapTypes.forEach((function(_this) { return function(mapType, index) { if (!found && mapType.layerId === _this.id) { found = true; _this.gMap.overlayMapTypes.removeAt(index); } }; })(this)); }; return MapTypeParentModel; })(BaseObject); return MapTypeParentModel; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapMarkersParentModel", [ "uiGmapIMarkerParentModel", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapMarkerChildModel", "uiGmap_async", "uiGmapClustererMarkerManager", "uiGmapMarkerManager", "$timeout", "uiGmapIMarker", "uiGmapPromise", "uiGmapGmapUtil", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, _async, ClustererMarkerManager, MarkerManager, $timeout, IMarker, uiGmapPromise, GmapUtil) { var MarkersParentModel; MarkersParentModel = (function(_super) { __extends(MarkersParentModel, _super); MarkersParentModel.include(GmapUtil); MarkersParentModel.include(ModelsWatcher); function MarkersParentModel(scope, element, attrs, map) { this.onDestroy = __bind(this.onDestroy, this); this.newChildMarker = __bind(this.newChildMarker, this); this.updateChild = __bind(this.updateChild, this); this.pieceMeal = __bind(this.pieceMeal, this); this.reBuildMarkers = __bind(this.reBuildMarkers, this); this.createMarkersFromScratch = __bind(this.createMarkersFromScratch, this); this.validateScope = __bind(this.validateScope, this); this.onWatch = __bind(this.onWatch, this); var self; MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map); self = this; this.scope.markerModels = new PropMap(); this.$log.info(this); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; this.setIdKey(scope); this.scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); this.watch('models', scope, !this.isTrue(attrs.modelsbyref)); this.watch('doCluster', scope); this.watch('clusterOptions', scope); this.watch('clusterEvents', scope); this.watch('fit', scope); this.watch('idKey', scope); this.gMarkerManager = void 0; this.createMarkersFromScratch(scope); } MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { if (propNameToWatch === "idKey" && newValue !== oldValue) { this.idKey = newValue; } if (this.doRebuildAll) { return this.reBuildMarkers(scope); } else { return this.pieceMeal(scope); } }; MarkersParentModel.prototype.validateScope = function(scope) { var modelsNotDefined; modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0; if (modelsNotDefined) { this.$log.error(this.constructor.name + ": no valid models attribute found"); } return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined; }; MarkersParentModel.prototype.createMarkersFromScratch = function(scope) { if (scope.doCluster) { if (scope.clusterEvents) { this.clusterInternalOptions = _.once((function(_this) { return function() { var self, _ref, _ref1, _ref2; self = _this; if (!_this.origClusterEvents) { _this.origClusterEvents = { click: (_ref = scope.clusterEvents) != null ? _ref.click : void 0, mouseout: (_ref1 = scope.clusterEvents) != null ? _ref1.mouseout : void 0, mouseover: (_ref2 = scope.clusterEvents) != null ? _ref2.mouseover : void 0 }; return _.extend(scope.clusterEvents, { click: function(cluster) { return self.maybeExecMappedEvent(cluster, 'click'); }, mouseout: function(cluster) { return self.maybeExecMappedEvent(cluster, 'mouseout'); }, mouseover: function(cluster) { return self.maybeExecMappedEvent(cluster, 'mouseover'); } }); } }; })(this))(); } if (scope.clusterOptions || scope.clusterEvents) { if (this.gMarkerManager === void 0) { this.gMarkerManager = new ClustererMarkerManager(this.map, void 0, scope.clusterOptions, this.clusterInternalOptions); } else { if (this.gMarkerManager.opt_options !== scope.clusterOptions) { this.gMarkerManager = new ClustererMarkerManager(this.map, void 0, scope.clusterOptions, this.clusterInternalOptions); } } } else { this.gMarkerManager = new ClustererMarkerManager(this.map); } } else { this.gMarkerManager = new MarkerManager(this.map); } return _async.waitOrGo(this, (function(_this) { return function() { return _async.each(scope.models, function(model) { return _this.newChildMarker(model, scope); }, false).then(function() { _this.gMarkerManager.draw(); if (scope.fit) { return _this.gMarkerManager.fit(); } }); }; })(this)).then((function(_this) { return function() { return _this.existingPieces = void 0; }; })(this)); }; MarkersParentModel.prototype.reBuildMarkers = function(scope) { var _ref; if (!scope.doRebuild && scope.doRebuild !== void 0) { return; } if ((_ref = this.scope.markerModels) != null ? _ref.length : void 0) { this.onDestroy(scope); } return this.createMarkersFromScratch(scope); }; MarkersParentModel.prototype.pieceMeal = function(scope) { var doChunk; doChunk = this.existingPieces != null ? false : _async.defaultChunkSize; if ((this.scope.models != null) && this.scope.models.length > 0 && this.scope.markerModels.length > 0) { return this.figureOutState(this.idKey, scope, this.scope.markerModels, this.modelKeyComparison, (function(_this) { return function(state) { var payload; payload = state; return _async.waitOrGo(_this, function() { return _async.each(payload.removals, function(child) { if (child != null) { if (child.destroy != null) { child.destroy(); } return _this.scope.markerModels.remove(child.id); } }, doChunk).then(function() { return _async.each(payload.adds, function(modelToAdd) { return _this.newChildMarker(modelToAdd, scope); }, doChunk); }).then(function() { return _async.each(payload.updates, function(update) { return _this.updateChild(update.child, update.model); }, doChunk); }).then(function() { if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) { _this.gMarkerManager.draw(); scope.markerModels = _this.scope.markerModels; if (scope.fit) { return _this.gMarkerManager.fit(); } } }); }).then(function() { return _this.existingPieces = void 0; }); }; })(this)); } else { return this.reBuildMarkers(scope); } }; MarkersParentModel.prototype.updateChild = function(child, model) { if (model[this.idKey] == null) { this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } return child.setMyScope(model, child.model, false); }; MarkersParentModel.prototype.newChildMarker = function(model, scope) { var child, childScope, doDrawSelf, keys; if (model[this.idKey] == null) { this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.$log.info('child', child, 'markers', this.scope.markerModels); childScope = scope.$new(true); childScope.events = scope.events; keys = {}; _.each(IMarker.scopeKeys, function(v, k) { return keys[k] = scope[k]; }); child = new MarkerChildModel(childScope, model, keys, this.map, this.DEFAULTS, this.doClick, this.gMarkerManager, doDrawSelf = false); this.scope.markerModels.put(model[this.idKey], child); return child; }; MarkersParentModel.prototype.onDestroy = function(scope) { return _async.waitOrGo(this, (function(_this) { return function() { _.each(_this.scope.markerModels.values(), function(model) { if (model != null) { return model.destroy(false); } }); delete _this.scope.markerModels; if (_this.gMarkerManager != null) { _this.gMarkerManager.clear(); } _this.scope.markerModels = new PropMap(); return uiGmapPromise.resolve(); }; })(this)); }; MarkersParentModel.prototype.maybeExecMappedEvent = function(cluster, fnName) { var pair, _ref; if (_.isFunction((_ref = this.scope.clusterEvents) != null ? _ref[fnName] : void 0)) { pair = this.mapClusterToMarkerModels(cluster); if (this.origClusterEvents[fnName]) { return this.origClusterEvents[fnName](pair.cluster, pair.mapped); } } }; MarkersParentModel.prototype.mapClusterToMarkerModels = function(cluster) { var gMarkers, mapped; gMarkers = cluster.getMarkers().values(); mapped = gMarkers.map((function(_this) { return function(g) { return _this.scope.markerModels[g.key].model; }; })(this)); return { cluster: cluster, mapped: mapped }; }; return MarkersParentModel; })(IMarkerParentModel); return MarkersParentModel; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapPolylinesParentModel", [ "$timeout", "uiGmapLogger", "uiGmapModelKey", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapPolylineChildModel", "uiGmap_async", function($timeout, Logger, ModelKey, ModelsWatcher, PropMap, PolylineChildModel, _async) { var PolylinesParentModel; return PolylinesParentModel = (function(_super) { __extends(PolylinesParentModel, _super); PolylinesParentModel.include(ModelsWatcher); function PolylinesParentModel(scope, element, attrs, gMap, defaults) { var self; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.defaults = defaults; this.modelKeyComparison = __bind(this.modelKeyComparison, this); this.setChildScope = __bind(this.setChildScope, this); this.createChild = __bind(this.createChild, this); this.pieceMeal = __bind(this.pieceMeal, this); this.createAllNew = __bind(this.createAllNew, this); this.watchIdKey = __bind(this.watchIdKey, this); this.createChildScopes = __bind(this.createChildScopes, this); this.watchOurScope = __bind(this.watchOurScope, this); this.watchDestroy = __bind(this.watchDestroy, this); this.rebuildAll = __bind(this.rebuildAll, this); this.doINeedToWipe = __bind(this.doINeedToWipe, this); this.watchModels = __bind(this.watchModels, this); this.watch = __bind(this.watch, this); PolylinesParentModel.__super__.constructor.call(this, scope); self = this; this.$log = Logger; this.plurals = new PropMap(); this.scopePropNames = ['path', 'stroke', 'clickable', 'draggable', 'editable', 'geodesic', 'icons', 'visible']; _.each(this.scopePropNames, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.models = void 0; this.firstTime = true; this.$log.info(this); this.watchOurScope(scope); this.createChildScopes(); } PolylinesParentModel.prototype.watch = function(scope, name, nameKey) { return scope.$watch(name, (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this[nameKey] = typeof newValue === 'function' ? newValue() : newValue; return _async.waitOrGo(_this, function() { return _async.each(_.values(_this.plurals), function(model) { return model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; }); }); } }; })(this)); }; PolylinesParentModel.prototype.watchModels = function(scope) { return scope.$watch('models', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (_this.doINeedToWipe(newValue)) { return _this.rebuildAll(scope, true, true); } else { return _this.createChildScopes(false); } } }; })(this), true); }; PolylinesParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; PolylinesParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return _async.waitOrGo(this, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(model) { return model.destroy(); }).then(function() { if (doDelete) { delete _this.plurals; } _this.plurals = new PropMap(); if (doCreate) { return _this.createChildScopes(); } }); }; })(this)); }; PolylinesParentModel.prototype.watchDestroy = function(scope) { return scope.$on("$destroy", (function(_this) { return function() { return _this.rebuildAll(scope, false, true); }; })(this)); }; PolylinesParentModel.prototype.watchOurScope = function(scope) { return _.each(this.scopePropNames, (function(_this) { return function(name) { var nameKey; nameKey = name + 'Key'; _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; return _this.watch(scope, name, nameKey); }; })(this)); }; PolylinesParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } if (angular.isUndefined(this.scope.models)) { this.$log.error("No models to create polylines from! I Need direct models!"); return; } if (this.gMap != null) { if (this.scope.models != null) { this.watchIdKey(this.scope); if (isCreatingFromScratch) { return this.createAllNew(this.scope, false); } else { return this.pieceMeal(this.scope, false); } } } }; PolylinesParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; PolylinesParentModel.prototype.createAllNew = function(scope, isArray) { if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } return _async.waitOrGo(this, (function(_this) { return function() { return _async.each(scope.models, function(model) { return _this.createChild(model, _this.gMap); }); }; })(this)).then((function(_this) { return function() { _this.firstTime = false; return _this.existingPieces = void 0; }; })(this)); }; PolylinesParentModel.prototype.pieceMeal = function(scope, isArray) { var doChunk; if (isArray == null) { isArray = true; } doChunk = this.existingPieces != null ? false : _async.defaultChunkSize; this.models = scope.models; if ((scope != null) && (scope.models != null) && scope.models.length > 0 && this.plurals.length > 0) { return this.figureOutState(this.idKey, scope, this.plurals, this.modelKeyComparison, (function(_this) { return function(state) { var payload; payload = state; return _async.waitOrGo(_this, function() { return _async.each(payload.removals, function(id) { var child; child = _this.plurals[id]; if (child != null) { child.destroy(); return _this.plurals.remove(id); } }).then(function() { return _async.each(payload.adds, function(modelToAdd) { return _this.createChild(modelToAdd, _this.gMap); }); }).then(function() { return _this.existingPieces = void 0; }); }); }; })(this)); } else { return this.rebuildAll(this.scope, true, true); } }; PolylinesParentModel.prototype.createChild = function(model, gMap) { var child, childScope; childScope = this.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); childScope["static"] = this.scope["static"]; child = new PolylineChildModel(childScope, this.attrs, gMap, this.defaults, model); if (model[this.idKey] == null) { this.$log.error("Polyline model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.plurals.put(model[this.idKey], child); return child; }; PolylinesParentModel.prototype.setChildScope = function(childScope, model) { _.each(this.scopePropNames, (function(_this) { return function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; })(this)); return childScope.model = model; }; PolylinesParentModel.prototype.modelKeyComparison = function(model1, model2) { return _.isEqual(this.evalModelHandle(model1, this.scope.path), this.evalModelHandle(model2, this.scope.path)); }; return PolylinesParentModel; })(ModelKey); } ]); }).call(this); (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.models.parent".ns()).factory("RectangleParentModel".ns(), [ "Logger".ns(), "GmapUtil".ns(), "EventsHelper".ns(), "RectangleOptionsBuilder".ns(), function($log, GmapUtil, EventsHelper, Builder) { var RectangleParentModel; return RectangleParentModel = (function(_super) { __extends(RectangleParentModel, _super); RectangleParentModel.include(GmapUtil); RectangleParentModel.include(EventsHelper); function RectangleParentModel(scope, element, attrs, map, DEFAULTS) { var bounds, clear, createBounds, dragging, fit, init, listeners, myListeners, rectangle, settingBoundsFromScope, updateBounds; this.scope = scope; this.attrs = attrs; this.map = map; this.DEFAULTS = DEFAULTS; bounds = void 0; dragging = false; myListeners = []; listeners = void 0; fit = (function(_this) { return function() { if (_this.isTrue(attrs.fit)) { return _this.fitMapBounds(_this.map, bounds); } }; })(this); createBounds = (function(_this) { return function() { var _ref, _ref1; if ((scope.bounds != null) && (((_ref = scope.bounds) != null ? _ref.sw : void 0) != null) && (((_ref1 = scope.bounds) != null ? _ref1.ne : void 0) != null) && _this.validateBoundPoints(scope.bounds)) { bounds = _this.convertBoundPoints(scope.bounds); return $log.info("new new bounds created: " + rectangle); } else if ((scope.bounds.getNorthEast != null) && (scope.bounds.getSouthWest != null)) { return bounds = scope.bounds; } else { if (typeof bound !== "undefined" && bound !== null) { return $log.error("Invalid bounds for newValue: " + (JSON.stringify(scope.bounds))); } } }; })(this); createBounds(); rectangle = new google.maps.Rectangle(this.buildOpts(bounds)); $log.info("rectangle created: " + rectangle); settingBoundsFromScope = false; updateBounds = (function(_this) { return function() { var b, ne, sw; b = rectangle.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); if (settingBoundsFromScope) { return; } return scope.$evalAsync(function(s) { if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) { s.bounds.ne = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.sw = { latitude: sw.lat(), longitude: sw.lng() }; } if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) { return s.bounds = b; } }); }; })(this); init = (function(_this) { return function() { fit(); _this.removeEvents(myListeners); myListeners.push(google.maps.event.addListener(rectangle, "dragstart", function() { return dragging = true; })); myListeners.push(google.maps.event.addListener(rectangle, "dragend", function() { dragging = false; return updateBounds(); })); return myListeners.push(google.maps.event.addListener(rectangle, "bounds_changed", function() { if (dragging) { return; } return updateBounds(); })); }; })(this); clear = (function(_this) { return function() { _this.removeEvents(myListeners); if (listeners != null) { _this.removeEvents(listeners); } return rectangle.setMap(null); }; })(this); if (bounds != null) { init(); } scope.$watch("bounds", (function(newValue, oldValue) { var isNew; if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) { return; } settingBoundsFromScope = true; if (newValue == null) { clear(); return; } if (bounds == null) { isNew = true; } else { fit(); } createBounds(); rectangle.setBounds(bounds); settingBoundsFromScope = false; if (isNew && (bounds != null)) { return init(); } }), true); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.isEqual(newVals, oldVals)) { if ((bounds != null) && (newVals != null)) { return rectangle.setOptions(_this.buildOpts(bounds)); } } }; })(this); this.props.push('bounds'); this.watchProps(this.props); if (attrs.events != null) { listeners = this.setEvents(rectangle, scope, scope); scope.$watch("events", (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (listeners != null) { _this.removeEvents(listeners); } return listeners = _this.setEvents(rectangle, scope, scope); } }; })(this)); } scope.$on("$destroy", (function(_this) { return function() { return clear(); }; })(this)); $log.info(this); } return RectangleParentModel; })(Builder); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.models.parent".ns()).factory("SearchBoxParentModel".ns(), [ "BaseObject".ns(), "Logger".ns(), "EventsHelper".ns(), '$timeout', '$http', '$templateCache', function(BaseObject, Logger, EventsHelper, $timeout, $http, $templateCache) { var SearchBoxParentModel; SearchBoxParentModel = (function(_super) { __extends(SearchBoxParentModel, _super); SearchBoxParentModel.include(EventsHelper); function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) { var controlDiv; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.ctrlPosition = ctrlPosition; this.template = template; this.$log = $log != null ? $log : Logger; this.getBounds = __bind(this.getBounds, this); this.setBounds = __bind(this.setBounds, this); this.createSearchBox = __bind(this.createSearchBox, this); this.addToParentDiv = __bind(this.addToParentDiv, this); this.addAsMapControl = __bind(this.addAsMapControl, this); this.init = __bind(this.init, this); if (this.attrs.template == null) { this.$log.error("template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!"); return; } controlDiv = angular.element('<div></div>'); controlDiv.append(this.template); this.input = controlDiv.find('input')[0]; this.init(); } SearchBoxParentModel.prototype.init = function() { this.createSearchBox(); if (this.attrs.parentdiv != null) { this.addToParentDiv(); } else { this.addAsMapControl(); } this.listener = google.maps.event.addListener(this.searchBox, 'places_changed', (function(_this) { return function() { return _this.places = _this.searchBox.getPlaces(); }; })(this)); this.listeners = this.setEvents(this.searchBox, this.scope, this.scope); this.$log.info(this); this.scope.$watch("options", (function(_this) { return function(newValue, oldValue) { if (angular.isObject(newValue)) { if (newValue.bounds != null) { return _this.setBounds(newValue.bounds); } } }; })(this), true); return this.scope.$on("$destroy", (function(_this) { return function() { return _this.searchBox = null; }; })(this)); }; SearchBoxParentModel.prototype.addAsMapControl = function() { return this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input); }; SearchBoxParentModel.prototype.addToParentDiv = function() { this.parentDiv = angular.element(document.getElementById(this.scope.parentdiv)); return this.parentDiv.append(this.input); }; SearchBoxParentModel.prototype.createSearchBox = function() { return this.searchBox = new google.maps.places.SearchBox(this.input, this.scope.options); }; SearchBoxParentModel.prototype.setBounds = function(bounds) { if (angular.isUndefined(bounds.isEmpty)) { this.$log.error("Error: SearchBoxParentModel setBounds. Bounds not an instance of LatLngBounds."); } else { if (bounds.isEmpty() === false) { if (this.searchBox != null) { return this.searchBox.setBounds(bounds); } } } }; SearchBoxParentModel.prototype.getBounds = function() { return this.searchBox.getBounds(); }; return SearchBoxParentModel; })(BaseObject); return SearchBoxParentModel; } ]); }).call(this); /* WindowsChildModel generator where there are many ChildModels to a parent. */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api.models.parent".ns()).factory("WindowsParentModel".ns(), [ "IWindowParentModel".ns(), "ModelsWatcher".ns(), "PropMap".ns(), "WindowChildModel".ns(), "Linked".ns(), "_async".ns(), "Logger".ns(), '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise) { var WindowsParentModel; WindowsParentModel = (function(_super) { __extends(WindowsParentModel, _super); WindowsParentModel.include(ModelsWatcher); function WindowsParentModel(scope, element, attrs, ctrls, gMap, markersScope) { var self; this.gMap = gMap; this.markersScope = markersScope; this.interpolateContent = __bind(this.interpolateContent, this); this.setChildScope = __bind(this.setChildScope, this); this.createWindow = __bind(this.createWindow, this); this.setContentKeys = __bind(this.setContentKeys, this); this.pieceMealWindows = __bind(this.pieceMealWindows, this); this.createAllNewWindows = __bind(this.createAllNewWindows, this); this.watchIdKey = __bind(this.watchIdKey, this); this.createChildScopesWindows = __bind(this.createChildScopesWindows, this); this.watchOurScope = __bind(this.watchOurScope, this); this.watchDestroy = __bind(this.watchDestroy, this); this.rebuildAll = __bind(this.rebuildAll, this); this.doINeedToWipe = __bind(this.doINeedToWipe, this); this.watchModels = __bind(this.watchModels, this); this.go = __bind(this.go, this); WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache); self = this; this.windows = new PropMap(); this.scopePropNames = ['coords', 'template', 'templateUrl', 'templateParameter', 'isIconVisibleOnClick', 'closeClick', 'options', 'show']; _.each(this.scopePropNames, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.linked = new Linked(scope, element, attrs, ctrls); this.models = void 0; this.contentKeys = void 0; this.isIconVisibleOnClick = void 0; this.firstTime = true; this.firstWatchModels = true; this.$log.info(self); this.parentScope = void 0; this.go(scope); } WindowsParentModel.prototype.go = function(scope) { this.watchOurScope(scope); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); return this.createChildScopesWindows(); }; WindowsParentModel.prototype.watchModels = function(scope) { return scope.$watch('models', (function(_this) { return function(newValue, oldValue) { var doScratch; if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) { _this.firstWatchModels = false; if (_this.doRebuildAll || _this.doINeedToWipe(newValue)) { return _this.rebuildAll(scope, true, true); } else { doScratch = _this.windows.length === 0; if (_this.existingPieces != null) { return _this.existingPieces.then(function() { return _this.createChildScopesWindows(doScratch); }); } else { return _this.createChildScopesWindows(doScratch); } } } }; })(this), true); }; WindowsParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.windows.length > 0 && newValueIsEmpty; }; WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { return _async.waitOrGo(this, (function(_this) { return function() { return _async.each(_this.windows.values(), function(model) { return model.destroy(); }).then(function() { if (doDelete) { delete _this.windows; } _this.windows = new PropMap(); if (doCreate) { _this.createChildScopesWindows(); } return uiGmapPromise.resolve(); }); }; })(this)); }; WindowsParentModel.prototype.watchDestroy = function(scope) { return scope.$on("$destroy", (function(_this) { return function() { _this.firstWatchModels = true; _this.firstTime = true; return _this.rebuildAll(scope, false, true); }; })(this)); }; WindowsParentModel.prototype.watchOurScope = function(scope) { return _.each(this.scopePropNames, (function(_this) { return function(name) { var nameKey; nameKey = name + 'Key'; return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; }; })(this)); }; WindowsParentModel.prototype.createChildScopesWindows = function(isCreatingFromScratch) { var modelsNotDefined, _ref, _ref1; if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } /* being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl) we will assume that all scope values are string expressions either pointing to a key (propName) or using 'self' to point the model as container/object of interest. This may force redundant information into the model, but this appears to be the most flexible approach. */ this.isIconVisibleOnClick = true; if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) { this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick; } modelsNotDefined = angular.isUndefined(this.linked.scope.models); if (modelsNotDefined && (this.markersScope === void 0 || (((_ref = this.markersScope) != null ? _ref.markerModels : void 0) === void 0 || ((_ref1 = this.markersScope) != null ? _ref1.models : void 0) === void 0))) { this.$log.error("No models to create windows from! Need direct models or models derrived from markers!"); return; } if (this.gMap != null) { if (this.linked.scope.models != null) { this.watchIdKey(this.linked.scope); if (isCreatingFromScratch) { return this.createAllNewWindows(this.linked.scope, false); } else { return this.pieceMealWindows(this.linked.scope, false); } } else { this.parentScope = this.markersScope; this.watchIdKey(this.parentScope); if (isCreatingFromScratch) { return this.createAllNewWindows(this.markersScope, true, 'markerModels', false); } else { return this.pieceMealWindows(this.markersScope, true, 'markerModels', false); } } } }; WindowsParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; WindowsParentModel.prototype.createAllNewWindows = function(scope, hasGMarker, modelsPropToIterate, isArray) { if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } this.setContentKeys(scope.models); return _async.waitOrGo(this, (function(_this) { return function() { return _async.each(scope.models, function(model) { var gMarker, _ref; gMarker = hasGMarker ? (_ref = scope[modelsPropToIterate][[model[_this.idKey]]]) != null ? _ref.gMarker : void 0 : void 0; return _this.createWindow(model, gMarker, _this.gMap); }); }; })(this)).then((function(_this) { return function() { return _this.firstTime = false; }; })(this)); }; WindowsParentModel.prototype.pieceMealWindows = function(scope, hasGMarker, modelsPropToIterate, isArray) { var doChunk; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = true; } doChunk = this.existingPieces != null ? false : _async.defaultChunkSize; this.models = scope.models; if ((scope != null) && (scope.models != null) && scope.models.length > 0 && this.windows.length > 0) { return this.figureOutState(this.idKey, scope, this.windows, this.modelKeyComparison, (function(_this) { return function(state) { var payload; payload = state; return _async.waitOrGo(_this, function() { return _async.each(payload.removals, function(child) { if (child != null) { _this.windows.remove(child.id); if (child.destroy != null) { return child.destroy(true); } } }, doChunk).then(function() { return _async.each(payload.adds, function(modelToAdd) { var gMarker, _ref; gMarker = (_ref = scope[modelsPropToIterate][modelToAdd[_this.idKey]]) != null ? _ref.gMarker : void 0; if (!gMarker) { throw "Gmarker undefined"; } return _this.createWindow(modelToAdd, gMarker, _this.gMap); }, doChunk); }); }).then(function() { return _this.existingPieces = void 0; })["catch"](function(e) { return $log.error("Error while pieceMealing Windows!"); }); }; })(this)); } else { return this.rebuildAll(this.scope, true, true); } }; WindowsParentModel.prototype.setContentKeys = function(models) { if (models.length > 0) { return this.contentKeys = Object.keys(models[0]); } }; WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) { var child, childScope, fakeElement, opts, _ref, _ref1; childScope = this.linked.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); fakeElement = { html: (function(_this) { return function() { return _this.interpolateContent(_this.linked.element.html(), model); }; })(this) }; this.DEFAULTS = this.markersScope ? model[this.optionsKey] || {} : this.DEFAULTS; opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS); child = new WindowChildModel(model, childScope, opts, this.isIconVisibleOnClick, gMap, (_ref = this.markersScope) != null ? (_ref1 = _ref.markerModels[model[this.idKey]]) != null ? _ref1.scope : void 0 : void 0, fakeElement, false, true); if (model[this.idKey] == null) { this.$log.error("Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.windows.put(model[this.idKey], child); return child; }; WindowsParentModel.prototype.setChildScope = function(childScope, model) { _.each(this.scopePropNames, (function(_this) { return function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; })(this)); return childScope.model = model; }; WindowsParentModel.prototype.interpolateContent = function(content, model) { var exp, interpModel, key, _i, _len, _ref; if (this.contentKeys === void 0 || this.contentKeys.length === 0) { return; } exp = $interpolate(content); interpModel = {}; _ref = this.contentKeys; for (_i = 0, _len = _ref.length; _i < _len; _i++) { key = _ref[_i]; interpModel[key] = model[key]; } return exp(interpModel); }; return WindowsParentModel; })(IWindowParentModel); return WindowsParentModel; } ]); }).call(this); (function() { angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapCircle", [ "uiGmapICircle", "uiGmapCircleParentModel", function(ICircle, CircleParentModel) { return _.extend(ICircle, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new CircleParentModel(scope, element, attrs, map); }; })(this)); } }); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapControl", [ "uiGmapIControl", "$http", "$templateCache", "$compile", "$controller", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) { var Control; return Control = (function(_super) { __extends(Control, _super); function Control() { this.link = __bind(this.link, this); Control.__super__.constructor.call(this); } Control.prototype.link = function(scope, element, attrs, ctrl) { return GoogleMapApi.then((function(_this) { return function(maps) { var index, position; if (angular.isUndefined(scope.template)) { _this.$log.error('mapControl: could not find a valid template property'); return; } index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0; position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER'; if (!maps.ControlPosition[position]) { _this.$log.error('mapControl: invalid position property'); return; } return IControl.mapPromise(scope, ctrl).then(function(map) { var control, controlDiv; control = void 0; controlDiv = angular.element('<div></div>'); return $http.get(scope.template, { cache: $templateCache }).success(function(template) { var templateCtrl, templateScope; templateScope = scope.$new(); controlDiv.append(template); if (index) { controlDiv[0].index = index; } if (angular.isDefined(scope.controller)) { templateCtrl = $controller(scope.controller, { $scope: templateScope }); controlDiv.children().data('$ngControllerController', templateCtrl); } return control = $compile(controlDiv.children())(templateScope); }).error(function(error) { return _this.$log.error('mapControl: template could not be found'); }).then(function() { return map.controls[google.maps.ControlPosition[position]].push(control[0]); }); }); }; })(this)); }; return Control; })(IControl); } ]); }).call(this); (function() { angular.module("google-maps.directives.api".ns()).factory("DrawingManager".ns(), [ "IDrawingManager".ns(), "DrawingManagerParentModel".ns(), function(IDrawingManager, DrawingManagerParentModel) { return _.extend(IDrawingManager, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new DrawingManagerParentModel(scope, element, attrs, map); }; })(this)); } }); } ]); }).call(this); /* - Link up Polygons to be sent back to a controller - inject the draw function into a controllers scope so that controller can call the directive to draw on demand - draw function creates the DrawFreeHandChildModel which manages itself */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api".ns()).factory('ApiFreeDrawPolygons'.ns(), [ "Logger".ns(), 'BaseObject'.ns(), "CtrlHandle".ns(), "DrawFreeHandChildModel".ns(), function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel) { var FreeDrawPolygons; return FreeDrawPolygons = (function(_super) { __extends(FreeDrawPolygons, _super); function FreeDrawPolygons() { this.link = __bind(this.link, this); return FreeDrawPolygons.__super__.constructor.apply(this, arguments); } FreeDrawPolygons.include(CtrlHandle); FreeDrawPolygons.prototype.restrict = 'EMA'; FreeDrawPolygons.prototype.replace = true; FreeDrawPolygons.prototype.require = '^' + 'GoogleMap'.ns(); FreeDrawPolygons.prototype.scope = { polygons: '=', draw: '=' }; FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) { return this.mapPromise(scope, ctrl).then((function(_this) { return function(map) { var freeHand, listener; if (!scope.polygons) { return $log.error("No polygons to bind to!"); } if (!_.isArray(scope.polygons)) { return $log.error("Free Draw Polygons must be of type Array!"); } freeHand = new DrawFreeHandChildModel(map, scope.originalMapOpts); listener = void 0; return scope.draw = function() { if (typeof listener === "function") { listener(); } return freeHand.engage(scope.polygons).then(function() { var firstTime; firstTime = true; return listener = scope.$watch('polygons', function(newValue, oldValue) { var removals; if (firstTime) { firstTime = false; return; } removals = _.differenceObjects(oldValue, newValue); return removals.forEach(function(p) { return p.setMap(null); }); }); }); }; }; })(this)); }; return FreeDrawPolygons; })(BaseObject); } ]); }).call(this); (function() { angular.module("uiGmapgoogle-maps.directives.api").service("uiGmapICircle", [ function() { var DEFAULTS; DEFAULTS = {}; return { restrict: "EA", replace: true, require: '^' + 'uiGmapGoogleMap', scope: { center: "=center", radius: "=radius", stroke: "=stroke", fill: "=fill", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=", events: "=" } }; } ]); }).call(this); /* - interface for all controls to derive from - to enforce a minimum set of requirements - attributes - template - position - controller - index */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api".ns()).factory("IControl".ns(), [ "BaseObject".ns(), "Logger".ns(), "CtrlHandle".ns(), function(BaseObject, Logger, CtrlHandle) { var IControl; return IControl = (function(_super) { __extends(IControl, _super); IControl.extend(CtrlHandle); function IControl() { this.link = __bind(this.link, this); this.restrict = 'EA'; this.replace = true; this.require = '^' + 'GoogleMap'.ns(); this.scope = { template: '@template', position: '@position', controller: '@controller', index: '@index' }; this.$log = Logger; } IControl.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not implemented!!"); }; return IControl; })(BaseObject); } ]); }).call(this); (function() { angular.module("google-maps.directives.api".ns()).service("IDrawingManager".ns(), [ function() { return { restrict: "EA", replace: true, require: '^' + 'GoogleMap'.ns(), scope: { "static": "@", control: "=", options: "=" } }; } ]); }).call(this); /* - interface for all markers to derrive from - to enforce a minimum set of requirements - attributes - coords - icon - implementation needed on watches */ (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api".ns()).factory("IMarker".ns(), [ "Logger".ns(), "BaseObject".ns(), "CtrlHandle".ns(), function(Logger, BaseObject, CtrlHandle) { var IMarker; return IMarker = (function(_super) { __extends(IMarker, _super); IMarker.scopeKeys = { coords: '=coords', icon: '=icon', click: '&click', options: '=options', events: '=events', fit: '=fit', idKey: '=idkey', control: '=control' }; IMarker.keys = _.keys(IMarker.scopeKeys); IMarker.extend(CtrlHandle); function IMarker() { this.$log = Logger; this.restrict = 'EMA'; this.require = '^' + 'GoogleMap'.ns(); this.priority = -1; this.transclude = true; this.replace = true; this.scope = IMarker.scopeKeys; } return IMarker; })(BaseObject); } ]); }).call(this); (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api".ns()).factory("IPolygon".ns(), [ "GmapUtil".ns(), "BaseObject".ns(), "Logger".ns(), "CtrlHandle".ns(), function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolygon; return IPolygon = (function(_super) { __extends(IPolygon, _super); IPolygon.include(GmapUtil); IPolygon.extend(CtrlHandle); function IPolygon() {} IPolygon.prototype.restrict = "EMA"; IPolygon.prototype.replace = true; IPolygon.prototype.require = '^' + 'GoogleMap'.ns(); IPolygon.prototype.scope = { path: "=path", stroke: "=stroke", clickable: "=", draggable: "=", editable: "=", geodesic: "=", fill: "=", icons: "=icons", visible: "=", "static": "=", events: "=", zIndex: "=zindex", fit: "=", control: "=control" }; IPolygon.prototype.DEFAULTS = {}; IPolygon.prototype.$log = Logger; return IPolygon; })(BaseObject); } ]); }).call(this); (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api".ns()).factory("IPolyline".ns(), [ "GmapUtil".ns(), "BaseObject".ns(), "Logger".ns(), "CtrlHandle".ns(), function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolyline; return IPolyline = (function(_super) { __extends(IPolyline, _super); IPolyline.include(GmapUtil); IPolyline.extend(CtrlHandle); function IPolyline() {} IPolyline.prototype.restrict = "EMA"; IPolyline.prototype.replace = true; IPolyline.prototype.require = '^' + 'GoogleMap'.ns(); IPolyline.prototype.scope = { path: "=", stroke: "=", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=", visible: "=", "static": "=", fit: "=", events: "=" }; IPolyline.prototype.DEFAULTS = {}; IPolyline.prototype.$log = Logger; return IPolyline; })(BaseObject); } ]); }).call(this); (function() { angular.module("google-maps.directives.api".ns()).service("IRectangle".ns(), [ function() { "use strict"; var DEFAULTS; DEFAULTS = {}; return { restrict: "EMA", require: '^' + 'GoogleMap'.ns(), replace: true, scope: { bounds: "=", stroke: "=", clickable: "=", draggable: "=", editable: "=", fill: "=", visible: "=", events: "=" } }; } ]); }).call(this); /* - interface directive for all window(s) to derive from */ (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapIWindow", [ "uiGmapBaseObject", "uiGmapChildEvents", "uiGmapLogger", "uiGmapCtrlHandle", function(BaseObject, ChildEvents, Logger, CtrlHandle) { var IWindow; return IWindow = (function(_super) { __extends(IWindow, _super); IWindow.include(ChildEvents); IWindow.extend(CtrlHandle); function IWindow() { this.restrict = 'EMA'; this.template = void 0; this.transclude = true; this.priority = -100; this.require = '^' + 'GoogleMap'.ns(); this.replace = true; this.scope = { coords: '=coords', template: '=template', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick', options: '=options', control: '=control', show: '=show' }; this.$log = Logger; } return IWindow; })(BaseObject); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMap", [ "$timeout", '$q', "uiGmapLogger", "uiGmapGmapUtil", "uiGmapBaseObject", "uiGmapCtrlHandle", 'uiGmapIsReady', "uiGmapuuid", "uiGmapExtendGWin", "uiGmapExtendMarkerClusterer", "uiGmapGoogleMapsUtilV3", 'uiGmapGoogleMapApi', function($timeout, $q, $log, GmapUtil, BaseObject, CtrlHandle, IsReady, uuid, ExtendGWin, ExtendMarkerClusterer, GoogleMapsUtilV3, GoogleMapApi) { "use strict"; var DEFAULTS, Map, initializeItems; DEFAULTS = void 0; initializeItems = [GoogleMapsUtilV3, ExtendGWin, ExtendMarkerClusterer]; return Map = (function(_super) { __extends(Map, _super); Map.include(GmapUtil); function Map() { this.link = __bind(this.link, this); var ctrlFn, self; ctrlFn = function($scope) { var ctrlObj, retCtrl; retCtrl = void 0; $scope.$on('$destroy', function() { return IsReady.reset(); }); ctrlObj = CtrlHandle.handle($scope); $scope.ctrlType = 'Map'; $scope.deferred.promise.then(function() { return initializeItems.forEach(function(i) { return i.init(); }); }); ctrlObj.getMap = function() { return $scope.map; }; retCtrl = _.extend(this, ctrlObj); return retCtrl; }; this.controller = ["$scope", ctrlFn]; self = this; } Map.prototype.restrict = "EMA"; Map.prototype.transclude = true; Map.prototype.replace = false; Map.prototype.template = '<div class="angular-google-map"><div class="angular-google-map-container"></div><div ng-transclude style="display: none"></div></div>'; Map.prototype.scope = { center: "=", zoom: "=", dragging: "=", control: "=", options: "=", events: "=", eventOpts: "=", styles: "=", bounds: "=", update: '=' }; Map.prototype.link = function(scope, element, attrs) { var unbindCenterWatch; scope.idleAndZoomChanged = false; if (scope.center == null) { unbindCenterWatch = scope.$watch('center', (function(_this) { return function() { if (!scope.center) { return; } unbindCenterWatch(); return _this.link(scope, element, attrs); }; })(this)); return; } return GoogleMapApi.then((function(_this) { return function(maps) { var dragging, el, eventName, getEventHandler, mapOptions, opts, resolveSpawned, settingCenterFromScope, spawned, type, _m; DEFAULTS = { mapTypeId: maps.MapTypeId.ROADMAP }; spawned = IsReady.spawn(); resolveSpawned = function() { return spawned.deferred.resolve({ instance: spawned.instance, map: _m }); }; if (!_this.validateCoords(scope.center)) { $log.error("angular-google-maps: could not find a valid center property"); return; } if (!angular.isDefined(scope.zoom)) { $log.error("angular-google-maps: map zoom property not set"); return; } el = angular.element(element); el.addClass("angular-google-map"); opts = { options: {} }; if (attrs.options) { opts.options = scope.options; } if (attrs.styles) { opts.styles = scope.styles; } if (attrs.type) { type = attrs.type.toUpperCase(); if (google.maps.MapTypeId.hasOwnProperty(type)) { opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()]; } else { $log.error("angular-google-maps: invalid map type '" + attrs.type + "'"); } } mapOptions = angular.extend({}, DEFAULTS, opts, { center: _this.getCoords(scope.center), zoom: scope.zoom, bounds: scope.bounds }); _m = new google.maps.Map(el.find("div")[1], mapOptions); _m['_id'.ns()] = uuid.generate(); dragging = false; google.maps.event.addListenerOnce(_m, 'idle', function() { scope.deferred.resolve(_m); return resolveSpawned(); }); google.maps.event.addListener(_m, "dragstart", function() { var _ref; if (!((_ref = scope.update) != null ? _ref.lazy : void 0)) { dragging = true; return scope.$evalAsync(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); } }); google.maps.event.addListener(_m, "dragend", function() { var _ref; if (!((_ref = scope.update) != null ? _ref.lazy : void 0)) { dragging = false; return scope.$evalAsync(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); } }); google.maps.event.addListener(_m, "drag", function() { var c, _ref, _ref1, _ref2, _ref3; if (!((_ref = scope.update) != null ? _ref.lazy : void 0)) { c = _m.center; return $timeout(function() { var s; s = scope; if (angular.isDefined(s.center.type)) { s.center.coordinates[1] = c.lat(); return s.center.coordinates[0] = c.lng(); } else { s.center.latitude = c.lat(); return s.center.longitude = c.lng(); } }, (_ref1 = scope.eventOpts) != null ? (_ref2 = _ref1.debounce) != null ? (_ref3 = _ref2.debounce) != null ? _ref3.dragMs : void 0 : void 0 : void 0); } }); google.maps.event.addListener(_m, "zoom_changed", function() { var _ref, _ref1, _ref2; if (!((_ref = scope.update) != null ? _ref.lazy : void 0)) { if (scope.zoom !== _m.zoom) { return $timeout(function() { return scope.zoom = _m.zoom; }, (_ref1 = scope.eventOpts) != null ? (_ref2 = _ref1.debounce) != null ? _ref2.zoomMs : void 0 : void 0); } } }); settingCenterFromScope = false; google.maps.event.addListener(_m, "center_changed", function() { var c, _ref, _ref1, _ref2; if (!((_ref = scope.update) != null ? _ref.lazy : void 0)) { c = _m.center; if (settingCenterFromScope) { return; } return $timeout(function() { var s; s = scope; if (!_m.dragging) { if (angular.isDefined(s.center.type)) { if (s.center.coordinates[1] !== c.lat()) { s.center.coordinates[1] = c.lat(); } if (s.center.coordinates[0] !== c.lng()) { return s.center.coordinates[0] = c.lng(); } } else { if (s.center.latitude !== c.lat()) { s.center.latitude = c.lat(); } if (s.center.longitude !== c.lng()) { return s.center.longitude = c.lng(); } } } }, (_ref1 = scope.eventOpts) != null ? (_ref2 = _ref1.debounce) != null ? _ref2.centerMs : void 0 : void 0); } }); google.maps.event.addListener(_m, "idle", function() { var b, ne, sw; b = _m.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); return scope.$evalAsync(function(s) { var c, _ref; if ((_ref = s.update) != null ? _ref.lazy : void 0) { c = _m.center; if (angular.isDefined(s.center.type)) { if (s.center.coordinates[1] !== c.lat()) { s.center.coordinates[1] = c.lat(); } if (s.center.coordinates[0] !== c.lng()) { s.center.coordinates[0] = c.lng(); } } else { if (s.center.latitude !== c.lat()) { s.center.latitude = c.lat(); } if (s.center.longitude !== c.lng()) { s.center.longitude = c.lng(); } } } if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0) { s.bounds.northeast = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.southwest = { latitude: sw.lat(), longitude: sw.lng() }; } s.zoom = _m.zoom; return scope.idleAndZoomChanged = !scope.idleAndZoomChanged; }); }); if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) { getEventHandler = function(eventName) { return function() { return scope.events[eventName].apply(scope, [_m, eventName, arguments]); }; }; for (eventName in scope.events) { if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { google.maps.event.addListener(_m, eventName, getEventHandler(eventName)); } } } _m.getOptions = function() { return mapOptions; }; scope.map = _m; if ((attrs.control != null) && (scope.control != null)) { scope.control.refresh = function(maybeCoords) { var coords; if (_m == null) { return; } google.maps.event.trigger(_m, "resize"); if (((maybeCoords != null ? maybeCoords.latitude : void 0) != null) && ((maybeCoords != null ? maybeCoords.latitude : void 0) != null)) { coords = _this.getCoords(maybeCoords); if (_this.isTrue(attrs.pan)) { return _m.panTo(coords); } else { return _m.setCenter(coords); } } }; scope.control.getGMap = function() { return _m; }; scope.control.getMapOptions = function() { return mapOptions; }; } scope.$watch("center", (function(newValue, oldValue) { var coords; coords = _this.getCoords(newValue); if (coords.lat() === _m.center.lat() && coords.lng() === _m.center.lng()) { return; } settingCenterFromScope = true; if (!dragging) { if (!_this.validateCoords(newValue)) { $log.error("Invalid center for newValue: " + (JSON.stringify(newValue))); } if (_this.isTrue(attrs.pan) && scope.zoom === _m.zoom) { _m.panTo(coords); } else { _m.setCenter(coords); } } return settingCenterFromScope = false; }), true); scope.$watch("zoom", function(newValue, oldValue) { if (_.isEqual(newValue, oldValue)) { return; } return $timeout(function() { return _m.setZoom(newValue); }, 0, false); }); scope.$watch("bounds", function(newValue, oldValue) { var bounds, ne, sw; if (newValue === oldValue) { return; } if ((newValue.northeast.latitude == null) || (newValue.northeast.longitude == null) || (newValue.southwest.latitude == null) || (newValue.southwest.longitude == null)) { $log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue))); return; } ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude); sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude); bounds = new google.maps.LatLngBounds(sw, ne); return _m.fitBounds(bounds); }); return ['options', 'styles'].forEach(function(toWatch) { return scope.$watch(toWatch, function(newValue, oldValue) { var watchItem; watchItem = this.exp; if (_.isEqual(newValue, oldValue)) { return; } opts.options = newValue; if (_m != null) { return _m.setOptions(opts); } }); }, true); }; })(this)); }; return Map; })(BaseObject); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarker", [ "uiGmapIMarker", "uiGmapMarkerChildModel", "uiGmapMarkerManager", function(IMarker, MarkerChildModel, MarkerManager) { var Marker; return Marker = (function(_super) { __extends(Marker, _super); function Marker() { this.link = __bind(this.link, this); Marker.__super__.constructor.call(this); this.template = '<span class="angular-google-map-marker" ng-transclude></span>'; this.$log.info(this); } Marker.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Marker'; return _.extend(this, IMarker.handle($scope, $element)); } ]; Marker.prototype.link = function(scope, element, attrs, ctrl) { this.mapPromise = IMarker.mapPromise(scope, ctrl); this.mapPromise.then((function(_this) { return function(map) { var doClick, doDrawSelf, keys, m, trackModel; if (!_this.gMarkerManager) { _this.gMarkerManager = new MarkerManager(map); } keys = _.object(IMarker.keys, IMarker.keys); m = new MarkerChildModel(scope, scope, keys, map, {}, doClick = true, _this.gMarkerManager, doDrawSelf = false, trackModel = false); m.deferred.promise.then(function(gMarker) { return scope.deferred.resolve(gMarker); }); if (scope.control != null) { return scope.control.getGMarkers = _this.gMarkerManager.getGMarkers; } }; })(this)); return scope.$on('$destroy', (function(_this) { return function() { var _ref; if ((_ref = _this.gMarkerManager) != null) { _ref.clear(); } return _this.gMarkerManager = null; }; })(this)); }; return Marker; })(IMarker); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapMarkers", [ "uiGmapIMarker", "uiGmapMarkersParentModel", "uiGmap_sync", function(IMarker, MarkersParentModel, _sync) { var Markers; return Markers = (function(_super) { __extends(Markers, _super); function Markers($timeout) { this.link = __bind(this.link, this); Markers.__super__.constructor.call(this, $timeout); this.template = '<span class="angular-google-map-markers" ng-transclude></span>'; this.scope = _.extend(this.scope || {}, { idKey: '=idkey', doRebuildAll: '=dorebuildall', models: '=models', doCluster: '=docluster', clusterOptions: '=clusteroptions', clusterEvents: '=clusterevents', modelsByRef: '=modelsbyref' }); this.$log.info(this); } Markers.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Markers'; return _.extend(this, IMarker.handle($scope, $element)); } ]; Markers.prototype.link = function(scope, element, attrs, ctrl) { var parentModel, ready; parentModel = void 0; ready = (function(_this) { return function() { if (scope.control != null) { scope.control.getGMarkers = function() { var _ref; return (_ref = parentModel.gMarkerManager) != null ? _ref.getGMarkers() : void 0; }; scope.control.getChildMarkers = function() { return parentModel.markerModels; }; } return scope.deferred.resolve(); }; })(this); return IMarker.mapPromise(scope, ctrl).then((function(_this) { return function(map) { var mapScope; mapScope = ctrl.getScope(); mapScope.$watch('idleAndZoomChanged', function() { return parentModel.gMarkerManager.draw(); }); parentModel = new MarkersParentModel(scope, element, attrs, map); return parentModel.existingPieces.then(function() { return ready(); }); }; })(this)); }; return Markers; })(IMarker); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api".ns()).factory("Polygon".ns(), [ "IPolygon".ns(), "$timeout", "array-sync".ns(), "PolygonChildModel".ns(), function(IPolygon, $timeout, arraySync, PolygonChild) { var Polygon; return Polygon = (function(_super) { __extends(Polygon, _super); function Polygon() { this.link = __bind(this.link, this); return Polygon.__super__.constructor.apply(this, arguments); } Polygon.prototype.link = function(scope, element, attrs, mapCtrl) { var children, promise; children = []; promise = IPolygon.mapPromise(scope, mapCtrl); if (scope.control != null) { scope.control.getInstance = this; scope.control.polygons = children; scope.control.promise = promise; } return promise.then((function(_this) { return function(map) { return children.push(new PolygonChild(scope, attrs, map, _this.DEFAULTS)); }; })(this)); }; return Polygon; })(IPolygon); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api".ns()).factory("Polyline".ns(), [ "IPolyline".ns(), "$timeout", "array-sync".ns(), "PolylineChildModel".ns(), function(IPolyline, $timeout, arraySync, PolylineChildModel) { var Polyline; return Polyline = (function(_super) { __extends(Polyline, _super); function Polyline() { this.link = __bind(this.link, this); return Polyline.__super__.constructor.apply(this, arguments); } Polyline.prototype.link = function(scope, element, attrs, mapCtrl) { if (angular.isUndefined(scope.path) || scope.path === null || !this.validatePath(scope.path)) { this.$log.error("polyline: no valid path attribute found"); return; } return IPolyline.mapPromise(scope, mapCtrl).then((function(_this) { return function(map) { return new PolylineChildModel(scope, attrs, map, _this.DEFAULTS); }; })(this)); }; return Polyline; })(IPolyline); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("google-maps.directives.api".ns()).factory("Polylines".ns(), [ "IPolyline".ns(), "$timeout", "array-sync".ns(), "PolylinesParentModel".ns(), function(IPolyline, $timeout, arraySync, PolylinesParentModel) { var Polylines; return Polylines = (function(_super) { __extends(Polylines, _super); function Polylines() { this.link = __bind(this.link, this); Polylines.__super__.constructor.call(this); this.scope.idKey = '=idkey'; this.scope.models = '=models'; this.$log.info(this); } Polylines.prototype.link = function(scope, element, attrs, mapCtrl) { if (angular.isUndefined(scope.path) || scope.path === null) { this.$log.error("polylines: no valid path attribute found"); return; } if (!scope.models) { this.$log.error("polylines: no models found to create from"); return; } return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new PolylinesParentModel(scope, element, attrs, map, _this.DEFAULTS); }; })(this)); }; return Polylines; })(IPolyline); } ]); }).call(this); (function() { angular.module("google-maps.directives.api".ns()).factory("Rectangle".ns(), [ "Logger".ns(), "GmapUtil".ns(), "IRectangle".ns(), "RectangleParentModel".ns(), function($log, GmapUtil, IRectangle, RectangleParentModel) { return _.extend(IRectangle, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new RectangleParentModel(scope, element, attrs, map); }; })(this)); } }); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapWindow", [ "uiGmapIWindow", "uiGmapGmapUtil", "uiGmapWindowChildModel", function(IWindow, GmapUtil, WindowChildModel) { var Window; return Window = (function(_super) { __extends(Window, _super); Window.include(GmapUtil); function Window() { this.link = __bind(this.link, this); Window.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker']; this.template = '<span class="angular-google-maps-window" ng-transclude></span>'; this.$log.info(this); this.childWindows = []; } Window.prototype.link = function(scope, element, attrs, ctrls) { var markerCtrl, markerScope; markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; this.mapPromise = IWindow.mapPromise(scope, ctrls[0]); return this.mapPromise.then((function(_this) { return function(mapCtrl) { var isIconVisibleOnClick; isIconVisibleOnClick = true; if (angular.isDefined(attrs.isiconvisibleonclick)) { isIconVisibleOnClick = scope.isIconVisibleOnClick; } if (!markerCtrl) { _this.init(scope, element, isIconVisibleOnClick, mapCtrl); return; } return markerScope.deferred.promise.then(function(gMarker) { return _this.init(scope, element, isIconVisibleOnClick, mapCtrl, markerScope); }); }; })(this)); }; Window.prototype.init = function(scope, element, isIconVisibleOnClick, mapCtrl, markerScope) { var childWindow, defaults, gMarker, hasScopeCoords, opts; defaults = scope.options != null ? scope.options : {}; hasScopeCoords = (scope != null) && this.validateCoords(scope.coords); if ((markerScope != null ? markerScope['getGMarker'] : void 0) != null) { gMarker = markerScope.getGMarker(); } opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults; if (mapCtrl != null) { childWindow = new WindowChildModel({}, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element); this.childWindows.push(childWindow); scope.$on("$destroy", (function(_this) { return function() { _this.childWindows = _.withoutObjects(_this.childWindows, [childWindow], function(child1, child2) { return child1.scope.$id === child2.scope.$id; }); return _this.childWindows.length = 0; }; })(this)); } if (scope.control != null) { scope.control.getGWindows = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.gWin; }); }; })(this); scope.control.getChildWindows = (function(_this) { return function() { return _this.childWindows; }; })(this); scope.control.showWindow = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.showWindow(); }); }; })(this); scope.control.hideWindow = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.hideWindow(); }); }; })(this); } if ((this.onChildCreation != null) && (childWindow != null)) { return this.onChildCreation(childWindow); } }; return Window; })(IWindow); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapWindows", [ "uiGmapIWindow", "uiGmapWindowsParentModel", "uiGmapPromise", function(IWindow, WindowsParentModel, uiGmapPromise) { /* Windows directive where many windows map to the models property */ var Windows; return Windows = (function(_super) { __extends(Windows, _super); function Windows() { this.init = __bind(this.init, this); this.link = __bind(this.link, this); Windows.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarkers']; this.template = '<span class="angular-google-maps-windows" ng-transclude></span>'; this.scope.idKey = '=idkey'; this.scope.doRebuildAll = '=dorebuildall'; this.scope.models = '=models'; this.$log.debug(this); } Windows.prototype.link = function(scope, element, attrs, ctrls) { var mapScope, markerCtrl, markerScope; mapScope = ctrls[0].getScope(); markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; return mapScope.deferred.promise.then((function(_this) { return function(map) { var promise, _ref; promise = (markerScope != null ? (_ref = markerScope.deferred) != null ? _ref.promise : void 0 : void 0) || uiGmapPromise.resolve(); return promise.then(function() { var pieces, _ref1; pieces = (_ref1 = _this.parentModel) != null ? _ref1.existingPieces : void 0; if (pieces) { return pieces.then(function() { return _this.init(scope, element, attrs, ctrls, map, markerScope); }); } else { return _this.init(scope, element, attrs, ctrls, map, markerScope); } }); }; })(this)); }; Windows.prototype.init = function(scope, element, attrs, ctrls, map, additionalScope) { var parentModel; parentModel = new WindowsParentModel(scope, element, attrs, ctrls, map, additionalScope); if (scope.control != null) { scope.control.getGWindows = (function(_this) { return function() { return parentModel.windows.map(function(child) { return child.gWin; }); }; })(this); return scope.control.getChildWindows = (function(_this) { return function() { return parentModel.windows; }; })(this); } }; return Windows; })(IWindow); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Nick Baugh - https://github.com/niftylettuce */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapGoogleMap", [ "uiGmapMap", function(Map) { return new Map(); } ]); }).call(this); /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module("google-maps".ns()).directive("Marker".ns(), [ "$timeout", "Marker".ns(), function($timeout, Marker) { return new Marker($timeout); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module("google-maps".ns()).directive("Markers".ns(), [ "$timeout", "Markers".ns(), function($timeout, Markers) { return new Markers($timeout); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module("google-maps".ns()).directive("Polygon".ns(), [ 'Polygon'.ns(), function(Polygon) { return new Polygon(); } ]); }).call(this); /* @authors Julian Popescu - https://github.com/jpopesculian Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module("google-maps".ns()).directive("Circle".ns(), [ "Circle".ns(), function(Circle) { return Circle; } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapPolyline", [ "uiGmapPolyline", function(Polyline) { return new Polyline(); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("google-maps".ns()).directive("Polylines".ns(), [ "Polylines".ns(), function(Polylines) { return new Polylines(); } ]); }).call(this); /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Chentsu Lin - https://github.com/ChenTsuLin */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapRectangle", [ "uiGmapLogger", "uiGmapRectangle", function($log, Rectangle) { return Rectangle; } ]); }).call(this); /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapWindow", [ "$timeout", "$compile", "$http", "$templateCache", "uiGmapWindow", function($timeout, $compile, $http, $templateCache, Window) { return new Window($timeout, $compile, $http, $templateCache); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapWindows", [ "$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) { return new Windows($timeout, $compile, $http, $templateCache, $interpolate); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready */ /* Map Layer directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. {attribute show optional} true (default) shows the trafficlayer otherwise it is hidden */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps").directive("uiGmapLayer", [ "$timeout", "uiGmapLogger", "uiGmapLayerParentModel", function($timeout, Logger, LayerParentModel) { var Layer; Layer = (function() { function Layer() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; this.require = '^' + 'GoogleMap'.ns(); this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>'; this.replace = true; this.scope = { show: "=show", type: "=type", namespace: "=namespace", options: '=options', onCreated: '&oncreated' }; } Layer.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (scope.onCreated != null) { return new LayerParentModel(scope, element, attrs, map, scope.onCreated); } else { return new LayerParentModel(scope, element, attrs, map); } }; })(this)); }; return Layer; })(); return new Layer(); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Adam Kreitals, [email protected] */ /* mapControl directive This directive is used to create a custom control element on an existing map. This directive creates a new scope. {attribute template required} string url of the template to be used for the control {attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER {attribute controller optional} string controller to be applied to the template {attribute index optional} number index for controlling the order of similarly positioned mapControl elements */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapMapControl", [ "uiGmapControl", function(Control) { return new Control(); } ]); }).call(this); (function() { angular.module("google-maps".ns()).directive("DrawingManager".ns(), [ "DrawingManager".ns(), function(DrawingManager) { return DrawingManager; } ]); }).call(this); /* angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicholas McCready - https://twitter.com/nmccready * Brunt of the work is in DrawFreeHandChildModel */ (function() { angular.module('google-maps'.ns()).directive('FreeDrawPolygons'.ns(), [ 'ApiFreeDrawPolygons'.ns(), function(FreeDrawPolygons) { return new FreeDrawPolygons(); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready */ /* Map Layer directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. {attribute show optional} true (default) shows the trafficlayer otherwise it is hidden */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("uiGmapgoogle-maps").directive("uiGmapMapType", [ "$timeout", "uiGmapLogger", "uiGmapMapTypeParentModel", function($timeout, Logger, MapTypeParentModel) { var MapType; MapType = (function() { function MapType() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; this.require = '^' + 'GoogleMap'.ns(); this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>'; this.replace = true; this.scope = { show: "=show", options: '=options', refresh: '=refresh', id: '@' }; } MapType.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new MapTypeParentModel(scope, element, attrs, map); }; })(this)); }; return MapType; })(); return new MapType(); } ]); }).call(this); /* @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready - Carrie Kengle - http://about.me/carrie */ /* Places Search Box directive This directive is used to create a Places Search Box. This directive creates a new scope. {attribute input required} HTMLInputElement {attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification) */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("google-maps".ns()).directive("SearchBox".ns(), [ "GoogleMapApi".ns(), "Logger".ns(), "SearchBoxParentModel".ns(), '$http', '$templateCache', function(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache) { var SearchBox; SearchBox = (function() { function SearchBox() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; this.require = '^' + 'GoogleMap'.ns(); this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-search\" ng-transclude></span>'; this.replace = true; this.scope = { template: '=template', position: '=position', options: '=options', events: '=events', parentdiv: '=parentdiv' }; } SearchBox.prototype.link = function(scope, element, attrs, mapCtrl) { return GoogleMapApi.then((function(_this) { return function(maps) { return $http.get(scope.template, { cache: $templateCache }).success(function(template) { return mapCtrl.getScope().deferred.promise.then(function(map) { var ctrlPosition; ctrlPosition = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_LEFT'; if (!maps.ControlPosition[ctrlPosition]) { _this.$log.error('searchBox: invalid position property'); return; } return new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, template); }); }); }; })(this)); }; return SearchBox; })(); return new SearchBox(); } ]); }).call(this); ;angular.module("google-maps.wrapped".ns()).service("uuid".ns(), function() { //BEGIN REPLACE /* Version: core-1.0 The MIT License: Copyright (c) 2012 LiosK. */ function UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+"-"+b(a(16),4)+"-"+b(16384|a(12),4)+"-"+b(32768|a(14),4)+"-"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN};UUID._ha=function(a,b){for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e)d&1&&(c=e+c);return c}; //END REPLACE return UUID; });;// wrap the utility libraries needed in ./lib // http://google-maps-utility-library-v3.googlecode.com/svn/ angular.module('google-maps.wrapped'.ns()).service('GoogleMapsUtilV3'.ns(), function () { return { init: _.once(function () { //BEGIN REPLACE /*! angular-google-maps 2.0.7 2014-11-04 * AngularJS directives for Google Maps * git: https://github.com/angular-ui/angular-google-maps.git */ /** * @name InfoBox * @version 1.1.12 [December 11, 2012] * @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google) * @copyright Copyright 2010 Gary Little [gary at luxcentral.com] * @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class. * <p> * An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several * additional properties for advanced styling. An InfoBox can also be used as a map label. * <p> * An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>. */ /*! * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint browser:true */ /*global google */ /** * @name InfoBoxOptions * @class This class represents the optional parameter passed to the {@link InfoBox} constructor. * @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node). * @property {boolean} [disableAutoPan=false] Disable auto-pan on <tt>open</tt>. * @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum. * @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox * (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>) * to the map pixel corresponding to <tt>position</tt>. * @property {LatLng} position The geographic location at which to display the InfoBox. * @property {number} zIndex The CSS z-index style value for the InfoBox. * Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property. * @property {string} [boxClass="infoBox"] The name of the CSS class defining the styles for the InfoBox container. * @property {Object} [boxStyle] An object literal whose properties define specific CSS * style values to be applied to the InfoBox. Style values defined here override those that may * be defined in the <code>boxClass</code> style sheet. If this property is changed after the * InfoBox has been created, all previously set styles (except those defined in the style sheet) * are removed from the InfoBox before the new style values are applied. * @property {string} closeBoxMargin The CSS margin style value for the close box. * The default is "2px" (a 2-pixel margin on all sides). * @property {string} closeBoxURL The URL of the image representing the close box. * Note: The default is the URL for Google's standard close box. * Set this property to "" if no close box is required. * @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the * map edge after an auto-pan. * @property {boolean} [isHidden=false] Hide the InfoBox on <tt>open</tt>. * [Deprecated in favor of the <tt>visible</tt> property.] * @property {boolean} [visible=true] Show the InfoBox on <tt>open</tt>. * @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code> * location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned). * @property {string} pane The pane where the InfoBox is to appear (default is "floatPane"). * Set the pane to "mapPane" if the InfoBox is being used as a map label. * Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object. * @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout, * mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox * (default is <tt>false</tt> to mimic the behavior of a <tt>google.maps.InfoWindow</tt>). Set * this property to <tt>true</tt> if the InfoBox is being used as a map label. */ /** * Creates an InfoBox with the options specified in {@link InfoBoxOptions}. * Call <tt>InfoBox.open</tt> to add the box to the map. * @constructor * @param {InfoBoxOptions} [opt_opts] */ function InfoBox(opt_opts) { opt_opts = opt_opts || {}; google.maps.OverlayView.apply(this, arguments); // Standard options (in common with google.maps.InfoWindow): // this.content_ = opt_opts.content || ""; this.disableAutoPan_ = opt_opts.disableAutoPan || false; this.maxWidth_ = opt_opts.maxWidth || 0; this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0); this.position_ = opt_opts.position || new google.maps.LatLng(0, 0); this.zIndex_ = opt_opts.zIndex || null; // Additional options (unique to InfoBox): // this.boxClass_ = opt_opts.boxClass || "infoBox"; this.boxStyle_ = opt_opts.boxStyle || {}; this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px"; this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif"; if (opt_opts.closeBoxURL === "") { this.closeBoxURL_ = ""; } this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1); if (typeof opt_opts.visible === "undefined") { if (typeof opt_opts.isHidden === "undefined") { opt_opts.visible = true; } else { opt_opts.visible = !opt_opts.isHidden; } } this.isHidden_ = !opt_opts.visible; this.alignBottom_ = opt_opts.alignBottom || false; this.pane_ = opt_opts.pane || "floatPane"; this.enableEventPropagation_ = opt_opts.enableEventPropagation || false; this.div_ = null; this.closeListener_ = null; this.moveListener_ = null; this.contextListener_ = null; this.eventListeners_ = null; this.fixedWidthSet_ = null; } /* InfoBox extends OverlayView in the Google Maps API v3. */ InfoBox.prototype = new google.maps.OverlayView(); /** * Creates the DIV representing the InfoBox. * @private */ InfoBox.prototype.createInfoBoxDiv_ = function () { var i; var events; var bw; var me = this; // This handler prevents an event in the InfoBox from being passed on to the map. // var cancelHandler = function (e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; // This handler ignores the current event in the InfoBox and conditionally prevents // the event from being passed on to the map. It is used for the contextmenu event. // var ignoreHandler = function (e) { e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } if (!me.enableEventPropagation_) { cancelHandler(e); } }; if (!this.div_) { this.div_ = document.createElement("div"); this.setBoxStyle_(); if (typeof this.content_.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + this.content_; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(this.content_); } // Add the InfoBox DIV to the DOM this.getPanes()[this.pane_].appendChild(this.div_); this.addClickHandler_(); if (this.div_.style.width) { this.fixedWidthSet_ = true; } else { if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) { this.div_.style.width = this.maxWidth_; this.div_.style.overflow = "auto"; this.fixedWidthSet_ = true; } else { // The following code is needed to overcome problems with MSIE bw = this.getBoxWidths_(); this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px"; this.fixedWidthSet_ = false; } } this.panBox_(this.disableAutoPan_); if (!this.enableEventPropagation_) { this.eventListeners_ = []; // Cancel event propagation. // // Note: mousemove not included (to resolve Issue 152) events = ["mousedown", "mouseover", "mouseout", "mouseup", "click", "dblclick", "touchstart", "touchend", "touchmove"]; for (i = 0; i < events.length; i++) { this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler)); } // Workaround for Google bug that causes the cursor to change to a pointer // when the mouse moves over a marker underneath InfoBox. this.eventListeners_.push(google.maps.event.addDomListener(this.div_, "mouseover", function (e) { this.style.cursor = "default"; })); } this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler); /** * This event is fired when the DIV containing the InfoBox's content is attached to the DOM. * @name InfoBox#domready * @event */ google.maps.event.trigger(this, "domready"); } }; /** * Returns the HTML <IMG> tag for the close box. * @private */ InfoBox.prototype.getCloseBoxImg_ = function () { var img = ""; if (this.closeBoxURL_ !== "") { img = "<img"; img += " src='" + this.closeBoxURL_ + "'"; img += " align=right"; // Do this because Opera chokes on style='float: right;' img += " style='"; img += " position: relative;"; // Required by MSIE img += " cursor: pointer;"; img += " margin: " + this.closeBoxMargin_ + ";"; img += "'>"; } return img; }; /** * Adds the click handler to the InfoBox close box. * @private */ InfoBox.prototype.addClickHandler_ = function () { var closeBox; if (this.closeBoxURL_ !== "") { closeBox = this.div_.firstChild; this.closeListener_ = google.maps.event.addDomListener(closeBox, "click", this.getCloseClickHandler_()); } else { this.closeListener_ = null; } }; /** * Returns the function to call when the user clicks the close box of an InfoBox. * @private */ InfoBox.prototype.getCloseClickHandler_ = function () { var me = this; return function (e) { // 1.0.3 fix: Always prevent propagation of a close box click to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } /** * This event is fired when the InfoBox's close box is clicked. * @name InfoBox#closeclick * @event */ google.maps.event.trigger(me, "closeclick"); me.close(); }; }; /** * Pans the map so that the InfoBox appears entirely within the map's visible area. * @private */ InfoBox.prototype.panBox_ = function (disablePan) { var map; var bounds; var xOffset = 0, yOffset = 0; if (!disablePan) { map = this.getMap(); if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama if (!map.getBounds().contains(this.position_)) { // Marker not in visible area of map, so set center // of map to the marker position first. map.setCenter(this.position_); } bounds = map.getBounds(); var mapDiv = map.getDiv(); var mapWidth = mapDiv.offsetWidth; var mapHeight = mapDiv.offsetHeight; var iwOffsetX = this.pixelOffset_.width; var iwOffsetY = this.pixelOffset_.height; var iwWidth = this.div_.offsetWidth; var iwHeight = this.div_.offsetHeight; var padX = this.infoBoxClearance_.width; var padY = this.infoBoxClearance_.height; var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_); if (pixPosition.x < (-iwOffsetX + padX)) { xOffset = pixPosition.x + iwOffsetX - padX; } else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) { xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth; } if (this.alignBottom_) { if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) { yOffset = pixPosition.y + iwOffsetY - padY - iwHeight; } else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwOffsetY + padY - mapHeight; } } else { if (pixPosition.y < (-iwOffsetY + padY)) { yOffset = pixPosition.y + iwOffsetY - padY; } else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight; } } if (!(xOffset === 0 && yOffset === 0)) { // Move the map to the shifted center. // var c = map.getCenter(); map.panBy(xOffset, yOffset); } } } }; /** * Sets the style of the InfoBox by setting the style sheet and applying * other specific styles requested. * @private */ InfoBox.prototype.setBoxStyle_ = function () { var i, boxStyle; if (this.div_) { // Apply style values from the style sheet defined in the boxClass parameter: this.div_.className = this.boxClass_; // Clear existing inline style values: this.div_.style.cssText = ""; // Apply style values defined in the boxStyle parameter: boxStyle = this.boxStyle_; for (i in boxStyle) { if (boxStyle.hasOwnProperty(i)) { this.div_.style[i] = boxStyle[i]; } } // Fix up opacity style for benefit of MSIE: // if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") { this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")"; } // Apply required styles: // this.div_.style.position = "absolute"; this.div_.style.visibility = 'hidden'; if (this.zIndex_ !== null) { this.div_.style.zIndex = this.zIndex_; } } }; /** * Get the widths of the borders of the InfoBox. * @private * @return {Object} widths object (top, bottom left, right) */ InfoBox.prototype.getBoxWidths_ = function () { var computedStyle; var bw = {top: 0, bottom: 0, left: 0, right: 0}; var box = this.div_; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; } } else if (document.documentElement.currentStyle) { // MSIE if (box.currentStyle) { // The current styles may not be in pixel units, but assume they are (bad!) bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0; } } return bw; }; /** * Invoked when <tt>close</tt> is called. Do not call it directly. */ InfoBox.prototype.onRemove = function () { if (this.div_) { this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the InfoBox based on the current map projection and zoom level. */ InfoBox.prototype.draw = function () { this.createInfoBoxDiv_(); var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_); this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px"; if (this.alignBottom_) { this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px"; } else { this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px"; } if (this.isHidden_) { this.div_.style.visibility = 'hidden'; } else { this.div_.style.visibility = "visible"; } }; /** * Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>, * <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt> * properties have no affect until the current InfoBox is <tt>close</tt>d and a new one * is <tt>open</tt>ed. * @param {InfoBoxOptions} opt_opts */ InfoBox.prototype.setOptions = function (opt_opts) { if (typeof opt_opts.boxClass !== "undefined") { // Must be first this.boxClass_ = opt_opts.boxClass; this.setBoxStyle_(); } if (typeof opt_opts.boxStyle !== "undefined") { // Must be second this.boxStyle_ = opt_opts.boxStyle; this.setBoxStyle_(); } if (typeof opt_opts.content !== "undefined") { this.setContent(opt_opts.content); } if (typeof opt_opts.disableAutoPan !== "undefined") { this.disableAutoPan_ = opt_opts.disableAutoPan; } if (typeof opt_opts.maxWidth !== "undefined") { this.maxWidth_ = opt_opts.maxWidth; } if (typeof opt_opts.pixelOffset !== "undefined") { this.pixelOffset_ = opt_opts.pixelOffset; } if (typeof opt_opts.alignBottom !== "undefined") { this.alignBottom_ = opt_opts.alignBottom; } if (typeof opt_opts.position !== "undefined") { this.setPosition(opt_opts.position); } if (typeof opt_opts.zIndex !== "undefined") { this.setZIndex(opt_opts.zIndex); } if (typeof opt_opts.closeBoxMargin !== "undefined") { this.closeBoxMargin_ = opt_opts.closeBoxMargin; } if (typeof opt_opts.closeBoxURL !== "undefined") { this.closeBoxURL_ = opt_opts.closeBoxURL; } if (typeof opt_opts.infoBoxClearance !== "undefined") { this.infoBoxClearance_ = opt_opts.infoBoxClearance; } if (typeof opt_opts.isHidden !== "undefined") { this.isHidden_ = opt_opts.isHidden; } if (typeof opt_opts.visible !== "undefined") { this.isHidden_ = !opt_opts.visible; } if (typeof opt_opts.enableEventPropagation !== "undefined") { this.enableEventPropagation_ = opt_opts.enableEventPropagation; } if (this.div_) { this.draw(); } }; /** * Sets the content of the InfoBox. * The content can be plain text or an HTML DOM node. * @param {string|Node} content */ InfoBox.prototype.setContent = function (content) { this.content_ = content; if (this.div_) { if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } // Odd code required to make things work with MSIE. // if (!this.fixedWidthSet_) { this.div_.style.width = ""; } if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } // Perverse code required to make things work with MSIE. // (Ensures the close box does, in fact, float to the right.) // if (!this.fixedWidthSet_) { this.div_.style.width = this.div_.offsetWidth + "px"; if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } } this.addClickHandler_(); } /** * This event is fired when the content of the InfoBox changes. * @name InfoBox#content_changed * @event */ google.maps.event.trigger(this, "content_changed"); }; /** * Sets the geographic location of the InfoBox. * @param {LatLng} latlng */ InfoBox.prototype.setPosition = function (latlng) { this.position_ = latlng; if (this.div_) { this.draw(); } /** * This event is fired when the position of the InfoBox changes. * @name InfoBox#position_changed * @event */ google.maps.event.trigger(this, "position_changed"); }; /** * Sets the zIndex style for the InfoBox. * @param {number} index */ InfoBox.prototype.setZIndex = function (index) { this.zIndex_ = index; if (this.div_) { this.div_.style.zIndex = index; } /** * This event is fired when the zIndex of the InfoBox changes. * @name InfoBox#zindex_changed * @event */ google.maps.event.trigger(this, "zindex_changed"); }; /** * Sets the visibility of the InfoBox. * @param {boolean} isVisible */ InfoBox.prototype.setVisible = function (isVisible) { this.isHidden_ = !isVisible; if (this.div_) { this.div_.style.visibility = (this.isHidden_ ? "hidden" : "visible"); } }; /** * Returns the content of the InfoBox. * @returns {string} */ InfoBox.prototype.getContent = function () { return this.content_; }; /** * Returns the geographic location of the InfoBox. * @returns {LatLng} */ InfoBox.prototype.getPosition = function () { return this.position_; }; /** * Returns the zIndex for the InfoBox. * @returns {number} */ InfoBox.prototype.getZIndex = function () { return this.zIndex_; }; /** * Returns a flag indicating whether the InfoBox is visible. * @returns {boolean} */ InfoBox.prototype.getVisible = function () { var isVisible; if ((typeof this.getMap() === "undefined") || (this.getMap() === null)) { isVisible = false; } else { isVisible = !this.isHidden_; } return isVisible; }; /** * Shows the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.] */ InfoBox.prototype.show = function () { this.isHidden_ = false; if (this.div_) { this.div_.style.visibility = "visible"; } }; /** * Hides the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.] */ InfoBox.prototype.hide = function () { this.isHidden_ = true; if (this.div_) { this.div_.style.visibility = "hidden"; } }; /** * Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt> * (usually a <tt>google.maps.Marker</tt>) is specified, the position * of the InfoBox is set to the position of the <tt>anchor</tt>. If the * anchor is dragged to a new location, the InfoBox moves as well. * @param {Map|StreetViewPanorama} map * @param {MVCObject} [anchor] */ InfoBox.prototype.open = function (map, anchor) { var me = this; if (anchor) { this.position_ = anchor.getPosition(); this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () { me.setPosition(this.getPosition()); }); } this.setMap(map); if (this.div_) { this.panBox_(); } }; /** * Removes the InfoBox from the map. */ InfoBox.prototype.close = function () { var i; if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } if (this.eventListeners_) { for (i = 0; i < this.eventListeners_.length; i++) { google.maps.event.removeListener(this.eventListeners_[i]); } this.eventListeners_ = null; } if (this.moveListener_) { google.maps.event.removeListener(this.moveListener_); this.moveListener_ = null; } if (this.contextListener_) { google.maps.event.removeListener(this.contextListener_); this.contextListener_ = null; } this.setMap(null); };;/** * @name MarkerClustererPlus for Google Maps V3 * @version 2.1.1 [November 4, 2013] * @author Gary Little * @fileoverview * The library creates and manages per-zoom-level clusters for large amounts of markers. * <p> * This is an enhanced V3 implementation of the * <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/" * >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the * <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/" * >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little. * <p> * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It * adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>, * and <code>calculator</code> properties as well as support for four more events. It also allows * greater control over the styling of the text that appears on the cluster marker. The * documentation has been significantly improved and the overall code has been simplified and * polished. Very large numbers of markers can now be managed without causing Javascript timeout * errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been * deprecated. The new name is <code>click</code>, so please change your application code now. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @name ClusterIconStyle * @class This class represents the object for values in the <code>styles</code> array passed * to the {@link MarkerClusterer} constructor. The element in this array that is used to * style the cluster icon is determined by calling the <code>calculator</code> function. * * @property {string} url The URL of the cluster icon image file. Required. * @property {number} height The display height (in pixels) of the cluster icon. Required. * @property {number} width The display width (in pixels) of the cluster icon. Required. * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to * where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code> * where <code>yoffset</code> increases as you go down from center and <code>xoffset</code> * increases to the right of center. The default is <code>[0, 0]</code>. * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the * spot on the cluster icon that is to be aligned with the cluster position. The format is * <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and * <code>xoffset</code> increases to the right of the top-left corner of the icon. The default * anchor position is the center of the cluster icon. * @property {string} [textColor="black"] The color of the label text shown on the * cluster icon. * @property {number} [textSize=11] The size (in pixels) of the label text shown on the * cluster icon. * @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code> * property for the label text shown on the cluster icon. * @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code> * property for the label text shown on the cluster icon. * @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code> * property for the label text shown on the cluster icon. * @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code> * property for the label text shown on the cluster icon. * @property {string} [backgroundPosition="0 0"] The position of the cluster icon image * within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code> * (the same format as for the CSS <code>background-position</code> property). You must set * this property appropriately when the image defined by <code>url</code> represents a sprite * containing multiple images. Note that the position <i>must</i> be specified in px units. */ /** * @name ClusterIconInfo * @class This class is an object containing general information about a cluster icon. This is * the object that a <code>calculator</code> function returns. * * @property {string} text The text of the label to be shown on the cluster icon. * @property {number} index The index plus 1 of the element in the <code>styles</code> * array to be used to style the cluster icon. * @property {string} title The tooltip to display when the mouse moves over the cluster icon. * If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the * value of the <code>title</code> property passed to the MarkerClusterer. */ /** * A cluster icon. * * @constructor * @extends google.maps.OverlayView * @param {Cluster} cluster The cluster with which the icon is to be associated. * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons * to use for various cluster sizes. * @private */ function ClusterIcon(cluster, styles) { cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView); this.cluster_ = cluster; this.className_ = cluster.getMarkerClusterer().getClusterClass(); this.styles_ = styles; this.center_ = null; this.div_ = null; this.sums_ = null; this.visible_ = false; this.setMap(cluster.getMap()); // Note: this causes onAdd to be called } /** * Adds the icon to the DOM. */ ClusterIcon.prototype.onAdd = function () { var cClusterIcon = this; var cMouseDownInCluster; var cDraggingMapByCluster; this.div_ = document.createElement("div"); this.div_.className = this.className_; if (this.visible_) { this.show(); } this.getPanes().overlayMouseTarget.appendChild(this.div_); // Fix for Issue 157 this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () { cDraggingMapByCluster = cMouseDownInCluster; }); google.maps.event.addDomListener(this.div_, "mousedown", function () { cMouseDownInCluster = true; cDraggingMapByCluster = false; }); google.maps.event.addDomListener(this.div_, "click", function (e) { cMouseDownInCluster = false; if (!cDraggingMapByCluster) { var theBounds; var mz; var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when a cluster marker is clicked. * @name MarkerClusterer#click * @param {Cluster} c The cluster that was clicked. * @event */ google.maps.event.trigger(mc, "click", cClusterIcon.cluster_); google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name // The default click handler follows. Disable it by setting // the zoomOnClick property to false. if (mc.getZoomOnClick()) { // Zoom into the cluster. mz = mc.getMaxZoom(); theBounds = cClusterIcon.cluster_.getBounds(); mc.getMap().fitBounds(theBounds); // There is a fix for Issue 170 here: setTimeout(function () { mc.getMap().fitBounds(theBounds); // Don't zoom beyond the max zoom level if (mz !== null && (mc.getMap().getZoom() > mz)) { mc.getMap().setZoom(mz + 1); } }, 100); } // Prevent event propagation to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } } }); google.maps.event.addDomListener(this.div_, "mouseover", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves over a cluster marker. * @name MarkerClusterer#mouseover * @param {Cluster} c The cluster that the mouse moved over. * @event */ google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_); }); google.maps.event.addDomListener(this.div_, "mouseout", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves out of a cluster marker. * @name MarkerClusterer#mouseout * @param {Cluster} c The cluster that the mouse moved out of. * @event */ google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_); }); }; /** * Removes the icon from the DOM. */ ClusterIcon.prototype.onRemove = function () { if (this.div_ && this.div_.parentNode) { this.hide(); google.maps.event.removeListener(this.boundsChangedListener_); google.maps.event.clearInstanceListeners(this.div_); this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the icon. */ ClusterIcon.prototype.draw = function () { if (this.visible_) { var pos = this.getPosFromLatLng_(this.center_); this.div_.style.top = pos.y + "px"; this.div_.style.left = pos.x + "px"; } }; /** * Hides the icon. */ ClusterIcon.prototype.hide = function () { if (this.div_) { this.div_.style.display = "none"; } this.visible_ = false; }; /** * Positions and shows the icon. */ ClusterIcon.prototype.show = function () { if (this.div_) { var img = ""; // NOTE: values must be specified in px units var bp = this.backgroundPosition_.split(" "); var spriteH = parseInt(bp[0].trim(), 10); var spriteV = parseInt(bp[1].trim(), 10); var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; "; if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) { img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " + ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);"; } img += "'>"; this.div_.innerHTML = img + "<div style='" + "position: absolute;" + "top: " + this.anchorText_[0] + "px;" + "left: " + this.anchorText_[1] + "px;" + "color: " + this.textColor_ + ";" + "font-size: " + this.textSize_ + "px;" + "font-family: " + this.fontFamily_ + ";" + "font-weight: " + this.fontWeight_ + ";" + "font-style: " + this.fontStyle_ + ";" + "text-decoration: " + this.textDecoration_ + ";" + "text-align: center;" + "width: " + this.width_ + "px;" + "line-height:" + this.height_ + "px;" + "'>" + this.sums_.text + "</div>"; if (typeof this.sums_.title === "undefined" || this.sums_.title === "") { this.div_.title = this.cluster_.getMarkerClusterer().getTitle(); } else { this.div_.title = this.sums_.title; } this.div_.style.display = ""; } this.visible_ = true; }; /** * Sets the icon styles to the appropriate element in the styles array. * * @param {ClusterIconInfo} sums The icon label text and styles index. */ ClusterIcon.prototype.useStyle = function (sums) { this.sums_ = sums; var index = Math.max(0, sums.index - 1); index = Math.min(this.styles_.length - 1, index); var style = this.styles_[index]; this.url_ = style.url; this.height_ = style.height; this.width_ = style.width; this.anchorText_ = style.anchorText || [0, 0]; this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)]; this.textColor_ = style.textColor || "black"; this.textSize_ = style.textSize || 11; this.textDecoration_ = style.textDecoration || "none"; this.fontWeight_ = style.fontWeight || "bold"; this.fontStyle_ = style.fontStyle || "normal"; this.fontFamily_ = style.fontFamily || "Arial,sans-serif"; this.backgroundPosition_ = style.backgroundPosition || "0 0"; }; /** * Sets the position at which to center the icon. * * @param {google.maps.LatLng} center The latlng to set as the center. */ ClusterIcon.prototype.setCenter = function (center) { this.center_ = center; }; /** * Creates the cssText style parameter based on the position of the icon. * * @param {google.maps.Point} pos The position of the icon. * @return {string} The CSS style text. */ ClusterIcon.prototype.createCss = function (pos) { var style = []; style.push("cursor: pointer;"); style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;"); style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;"); return style.join(""); }; /** * Returns the position at which to place the DIV depending on the latlng. * * @param {google.maps.LatLng} latlng The position in latlng. * @return {google.maps.Point} The position in pixels. */ ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) { var pos = this.getProjection().fromLatLngToDivPixel(latlng); pos.x -= this.anchorIcon_[1]; pos.y -= this.anchorIcon_[0]; pos.x = parseInt(pos.x, 10); pos.y = parseInt(pos.y, 10); return pos; }; /** * Creates a single cluster that manages a group of proximate markers. * Used internally, do not call this constructor directly. * @constructor * @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this * cluster is associated. */ function Cluster(mc) { this.markerClusterer_ = mc; this.map_ = mc.getMap(); this.gridSize_ = mc.getGridSize(); this.minClusterSize_ = mc.getMinimumClusterSize(); this.averageCenter_ = mc.getAverageCenter(); this.markers_ = []; this.center_ = null; this.bounds_ = null; this.clusterIcon_ = new ClusterIcon(this, mc.getStyles()); } /** * Returns the number of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {number} The number of markers in the cluster. */ Cluster.prototype.getSize = function () { return this.markers_.length; }; /** * Returns the array of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {Array} The array of markers in the cluster. */ Cluster.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the center of the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {google.maps.LatLng} The center of the cluster. */ Cluster.prototype.getCenter = function () { return this.center_; }; /** * Returns the map with which the cluster is associated. * * @return {google.maps.Map} The map. * @ignore */ Cluster.prototype.getMap = function () { return this.map_; }; /** * Returns the <code>MarkerClusterer</code> object with which the cluster is associated. * * @return {MarkerClusterer} The associated marker clusterer. * @ignore */ Cluster.prototype.getMarkerClusterer = function () { return this.markerClusterer_; }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ Cluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); var markers = this.getMarkers(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } return bounds; }; /** * Removes the cluster from the map. * * @ignore */ Cluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = []; delete this.markers_; }; /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ Cluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. for (i = 0; i < mCount; i++) { this.markers_[i].setMap(null); } } else { marker.setMap(null); } this.updateIcon_(); return true; }; /** * Determines if a marker lies within the cluster's bounds. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker lies in the bounds. * @ignore */ Cluster.prototype.isMarkerInClusterBounds = function (marker) { return this.bounds_.contains(marker.getPosition()); }; /** * Calculates the extended bounds of the cluster with the grid. */ Cluster.prototype.calculateBounds_ = function () { var bounds = new google.maps.LatLngBounds(this.center_, this.center_); this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds); }; /** * Updates the cluster icon. */ Cluster.prototype.updateIcon_ = function () { var mCount = this.markers_.length; var mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { this.clusterIcon_.hide(); return; } if (mCount < this.minClusterSize_) { // Min cluster size not yet reached. this.clusterIcon_.hide(); return; } var numStyles = this.markerClusterer_.getStyles().length; var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles); this.clusterIcon_.setCenter(this.center_); this.clusterIcon_.useStyle(sums); this.clusterIcon_.show(); }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) { var i; if (this.markers_.indexOf) { return this.markers_.indexOf(marker) !== -1; } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { return true; } } } return false; }; /** * @name MarkerClustererOptions * @class This class represents the optional parameter passed to * the {@link MarkerClusterer} constructor. * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square. * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or * <code>null</code> if clustering is to be enabled at all zoom levels. * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is * clicked. You may want to set this to <code>false</code> if you have installed a handler * for the <code>click</code> event and it deals with zooming on its own. * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be * the average position of all markers in the cluster. If set to <code>false</code>, the * cluster marker is positioned at the location of the first marker added to the cluster. * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster * before the markers are hidden and a cluster marker appears. * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You * may want to set this to <code>true</code> to ensure that hidden markers are not included * in the marker count that appears on a cluster marker (this count is the value of the * <code>text</code> property of the result returned by the default <code>calculator</code>). * If set to <code>true</code> and you change the visibility of a marker being clustered, be * sure to also call <code>MarkerClusterer.repaint()</code>. * @property {string} [title=""] The tooltip to display when the mouse moves over a cluster * marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a * different tooltip for each cluster marker.) * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine * the text to be displayed on a cluster marker and the index indicating which style to use * for the cluster marker. The input parameters for the function are (1) the array of markers * represented by a cluster marker and (2) the number of cluster icon styles. It returns a * {@link ClusterIconInfo} object. The default <code>calculator</code> returns a * <code>text</code> property which is the number of markers in the cluster and an * <code>index</code> property which is one higher than the lowest integer such that * <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles * array, whichever is less. The <code>styles</code> array element used has an index of * <code>index</code> minus 1. For example, the default <code>calculator</code> returns a * <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code> * for a cluster icon representing 125 markers so the element used in the <code>styles</code> * array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code> * property that contains the text of the tooltip to be used for the cluster marker. If * <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code> * property for the MarkerClusterer. * @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles * for the cluster markers. Use this class to define CSS styles that are not set up by the code * that processes the <code>styles</code> array. * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles * of the cluster markers to be used. The element to be used to style a given cluster marker * is determined by the function defined by the <code>calculator</code> property. * The default is an array of {@link ClusterIconStyle} elements whose properties are derived * from the values for <code>imagePath</code>, <code>imageExtension</code>, and * <code>imageSizes</code>. * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that * have sizes that are some multiple (typically double) of their actual display size. Icons such * as these look better when viewed on high-resolution monitors such as Apple's Retina displays. * Note: if this property is <code>true</code>, sprites cannot be used as cluster icons. * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the * number of markers to be processed in a single batch when using a browser other than * Internet Explorer (for Internet Explorer, use the batchSizeIE property instead). * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is * being used, markers are processed in several batches with a small delay inserted between * each batch in an attempt to avoid Javascript timeout errors. Set this property to the * number of markers to be processed in a single batch; select as high a number as you can * without causing a timeout error in the browser. This number might need to be as low as 100 * if 15,000 markers are being managed, for example. * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH] * The full URL of the root name of the group of image files to use for cluster icons. * The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code> * where n is the image file number (1, 2, etc.). * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION] * The extension name for the cluster icon image files (e.g., <code>"png"</code> or * <code>"jpg"</code>). * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES] * An array of numbers containing the widths of the group of * <code>imagePath</code>n.<code>imageExtension</code> image files. * (The images are assumed to be square.) */ /** * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}. * @constructor * @extends google.maps.OverlayView * @param {google.maps.Map} map The Google map to attach to. * @param {Array.<google.maps.nggmap-marker>} [opt_markers] The markers to be added to the cluster. * @param {MarkerClustererOptions} [opt_options] The optional parameters. */ function MarkerClusterer(map, opt_markers, opt_options) { // MarkerClusterer implements google.maps.OverlayView interface. We use the // extend function to extend MarkerClusterer with google.maps.OverlayView // because it might not always be available when the code is defined so we // look for it at the last possible moment. If it doesn't exist now then // there is no point going ahead :) this.extend(MarkerClusterer, google.maps.OverlayView); opt_markers = opt_markers || []; opt_options = opt_options || {}; this.markers_ = []; this.clusters_ = []; this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; this.gridSize_ = opt_options.gridSize || 60; this.minClusterSize_ = opt_options.minimumClusterSize || 2; this.maxZoom_ = opt_options.maxZoom || null; this.styles_ = opt_options.styles || []; this.title_ = opt_options.title || ""; this.zoomOnClick_ = true; if (opt_options.zoomOnClick !== undefined) { this.zoomOnClick_ = opt_options.zoomOnClick; } this.averageCenter_ = false; if (opt_options.averageCenter !== undefined) { this.averageCenter_ = opt_options.averageCenter; } this.ignoreHidden_ = false; if (opt_options.ignoreHidden !== undefined) { this.ignoreHidden_ = opt_options.ignoreHidden; } this.enableRetinaIcons_ = false; if (opt_options.enableRetinaIcons !== undefined) { this.enableRetinaIcons_ = opt_options.enableRetinaIcons; } this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH; this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION; this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES; this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR; this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE; this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE; this.clusterClass_ = opt_options.clusterClass || "cluster"; if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) { // Try to avoid IE timeout when processing a huge number of markers: this.batchSize_ = this.batchSizeIE_; } this.setupStyles_(); this.addMarkers(opt_markers, true); this.setMap(map); // Note: this causes onAdd to be called } /** * Implementation of the onAdd interface method. * @ignore */ MarkerClusterer.prototype.onAdd = function () { var cMarkerClusterer = this; this.activeMap_ = this.getMap(); this.ready_ = true; this.repaint(); // Add the map event listeners this.listeners_ = [ google.maps.event.addListener(this.getMap(), "zoom_changed", function () { cMarkerClusterer.resetViewport_(false); // Workaround for this Google bug: when map is at level 0 and "-" of // zoom slider is clicked, a "zoom_changed" event is fired even though // the map doesn't zoom out any further. In this situation, no "idle" // event is triggered so the cluster markers that have been removed // do not get redrawn. Same goes for a zoom in at maxZoom. if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) { google.maps.event.trigger(this, "idle"); } }), google.maps.event.addListener(this.getMap(), "idle", function () { cMarkerClusterer.redraw_(); }) ]; }; /** * Implementation of the onRemove interface method. * Removes map event listeners and all cluster icons from the DOM. * All managed markers are also put back on the map. * @ignore */ MarkerClusterer.prototype.onRemove = function () { var i; // Put all the managed markers back on the map: for (i = 0; i < this.markers_.length; i++) { if (this.markers_[i].getMap() !== this.activeMap_) { this.markers_[i].setMap(this.activeMap_); } } // Remove all clusters: for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Remove map event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; }; /** * Implementation of the draw interface method. * @ignore */ MarkerClusterer.prototype.draw = function () {}; /** * Sets up the styles object. */ MarkerClusterer.prototype.setupStyles_ = function () { var i, size; if (this.styles_.length > 0) { return; } for (i = 0; i < this.imageSizes_.length; i++) { size = this.imageSizes_[i]; this.styles_.push({ url: this.imagePath_ + (i + 1) + "." + this.imageExtension_, height: size, width: size }); } }; /** * Fits the map to the bounds of the markers managed by the clusterer. */ MarkerClusterer.prototype.fitMapToMarkers = function () { var i; var markers = this.getMarkers(); var bounds = new google.maps.LatLngBounds(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } this.getMap().fitBounds(bounds); }; /** * Returns the value of the <code>gridSize</code> property. * * @return {number} The grid size. */ MarkerClusterer.prototype.getGridSize = function () { return this.gridSize_; }; /** * Sets the value of the <code>gridSize</code> property. * * @param {number} gridSize The grid size. */ MarkerClusterer.prototype.setGridSize = function (gridSize) { this.gridSize_ = gridSize; }; /** * Returns the value of the <code>minimumClusterSize</code> property. * * @return {number} The minimum cluster size. */ MarkerClusterer.prototype.getMinimumClusterSize = function () { return this.minClusterSize_; }; /** * Sets the value of the <code>minimumClusterSize</code> property. * * @param {number} minimumClusterSize The minimum cluster size. */ MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) { this.minClusterSize_ = minimumClusterSize; }; /** * Returns the value of the <code>maxZoom</code> property. * * @return {number} The maximum zoom level. */ MarkerClusterer.prototype.getMaxZoom = function () { return this.maxZoom_; }; /** * Sets the value of the <code>maxZoom</code> property. * * @param {number} maxZoom The maximum zoom level. */ MarkerClusterer.prototype.setMaxZoom = function (maxZoom) { this.maxZoom_ = maxZoom; }; /** * Returns the value of the <code>styles</code> property. * * @return {Array} The array of styles defining the cluster markers to be used. */ MarkerClusterer.prototype.getStyles = function () { return this.styles_; }; /** * Sets the value of the <code>styles</code> property. * * @param {Array.<ClusterIconStyle>} styles The array of styles to use. */ MarkerClusterer.prototype.setStyles = function (styles) { this.styles_ = styles; }; /** * Returns the value of the <code>title</code> property. * * @return {string} The content of the title text. */ MarkerClusterer.prototype.getTitle = function () { return this.title_; }; /** * Sets the value of the <code>title</code> property. * * @param {string} title The value of the title property. */ MarkerClusterer.prototype.setTitle = function (title) { this.title_ = title; }; /** * Returns the value of the <code>zoomOnClick</code> property. * * @return {boolean} True if zoomOnClick property is set. */ MarkerClusterer.prototype.getZoomOnClick = function () { return this.zoomOnClick_; }; /** * Sets the value of the <code>zoomOnClick</code> property. * * @param {boolean} zoomOnClick The value of the zoomOnClick property. */ MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) { this.zoomOnClick_ = zoomOnClick; }; /** * Returns the value of the <code>averageCenter</code> property. * * @return {boolean} True if averageCenter property is set. */ MarkerClusterer.prototype.getAverageCenter = function () { return this.averageCenter_; }; /** * Sets the value of the <code>averageCenter</code> property. * * @param {boolean} averageCenter The value of the averageCenter property. */ MarkerClusterer.prototype.setAverageCenter = function (averageCenter) { this.averageCenter_ = averageCenter; }; /** * Returns the value of the <code>ignoreHidden</code> property. * * @return {boolean} True if ignoreHidden property is set. */ MarkerClusterer.prototype.getIgnoreHidden = function () { return this.ignoreHidden_; }; /** * Sets the value of the <code>ignoreHidden</code> property. * * @param {boolean} ignoreHidden The value of the ignoreHidden property. */ MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) { this.ignoreHidden_ = ignoreHidden; }; /** * Returns the value of the <code>enableRetinaIcons</code> property. * * @return {boolean} True if enableRetinaIcons property is set. */ MarkerClusterer.prototype.getEnableRetinaIcons = function () { return this.enableRetinaIcons_; }; /** * Sets the value of the <code>enableRetinaIcons</code> property. * * @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property. */ MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) { this.enableRetinaIcons_ = enableRetinaIcons; }; /** * Returns the value of the <code>imageExtension</code> property. * * @return {string} The value of the imageExtension property. */ MarkerClusterer.prototype.getImageExtension = function () { return this.imageExtension_; }; /** * Sets the value of the <code>imageExtension</code> property. * * @param {string} imageExtension The value of the imageExtension property. */ MarkerClusterer.prototype.setImageExtension = function (imageExtension) { this.imageExtension_ = imageExtension; }; /** * Returns the value of the <code>imagePath</code> property. * * @return {string} The value of the imagePath property. */ MarkerClusterer.prototype.getImagePath = function () { return this.imagePath_; }; /** * Sets the value of the <code>imagePath</code> property. * * @param {string} imagePath The value of the imagePath property. */ MarkerClusterer.prototype.setImagePath = function (imagePath) { this.imagePath_ = imagePath; }; /** * Returns the value of the <code>imageSizes</code> property. * * @return {Array} The value of the imageSizes property. */ MarkerClusterer.prototype.getImageSizes = function () { return this.imageSizes_; }; /** * Sets the value of the <code>imageSizes</code> property. * * @param {Array} imageSizes The value of the imageSizes property. */ MarkerClusterer.prototype.setImageSizes = function (imageSizes) { this.imageSizes_ = imageSizes; }; /** * Returns the value of the <code>calculator</code> property. * * @return {function} the value of the calculator property. */ MarkerClusterer.prototype.getCalculator = function () { return this.calculator_; }; /** * Sets the value of the <code>calculator</code> property. * * @param {function(Array.<google.maps.nggmap-marker>, number)} calculator The value * of the calculator property. */ MarkerClusterer.prototype.setCalculator = function (calculator) { this.calculator_ = calculator; }; /** * Returns the value of the <code>batchSizeIE</code> property. * * @return {number} the value of the batchSizeIE property. */ MarkerClusterer.prototype.getBatchSizeIE = function () { return this.batchSizeIE_; }; /** * Sets the value of the <code>batchSizeIE</code> property. * * @param {number} batchSizeIE The value of the batchSizeIE property. */ MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) { this.batchSizeIE_ = batchSizeIE; }; /** * Returns the value of the <code>clusterClass</code> property. * * @return {string} the value of the clusterClass property. */ MarkerClusterer.prototype.getClusterClass = function () { return this.clusterClass_; }; /** * Sets the value of the <code>clusterClass</code> property. * * @param {string} clusterClass The value of the clusterClass property. */ MarkerClusterer.prototype.setClusterClass = function (clusterClass) { this.clusterClass_ = clusterClass; }; /** * Returns the array of markers managed by the clusterer. * * @return {Array} The array of markers managed by the clusterer. */ MarkerClusterer.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the number of markers managed by the clusterer. * * @return {number} The number of markers. */ MarkerClusterer.prototype.getTotalMarkers = function () { return this.markers_.length; }; /** * Returns the current array of clusters formed by the clusterer. * * @return {Array} The array of clusters formed by the clusterer. */ MarkerClusterer.prototype.getClusters = function () { return this.clusters_; }; /** * Returns the number of clusters formed by the clusterer. * * @return {number} The number of clusters formed by the clusterer. */ MarkerClusterer.prototype.getTotalClusters = function () { return this.clusters_.length; }; /** * Adds a marker to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {google.maps.Marker} marker The marker to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) { this.pushMarkerTo_(marker); if (!opt_nodraw) { this.redraw_(); } }; /** * Adds an array of markers to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {Array.<google.maps.nggmap-marker>} markers The markers to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) { var key; for (key in markers) { if (markers.hasOwnProperty(key)) { this.pushMarkerTo_(markers[key]); } } if (!opt_nodraw) { this.redraw_(); } }; /** * Pushes a marker to the clusterer. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.pushMarkerTo_ = function (marker) { // If the marker is draggable add a listener so we can update the clusters on the dragend: if (marker.getDraggable()) { var cMarkerClusterer = this; google.maps.event.addListener(marker, "dragend", function () { if (cMarkerClusterer.ready_) { this.isAdded = false; cMarkerClusterer.repaint(); } }); } marker.isAdded = false; this.markers_.push(marker); }; /** * Removes a marker from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the * marker was removed from the clusterer. * * @param {google.maps.Marker} marker The marker to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if the marker was removed from the clusterer. */ MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) { var removed = this.removeMarker_(marker); if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes an array of markers from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers * were removed from the clusterer. * * @param {Array.<google.maps.nggmap-marker>} markers The markers to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if markers were removed from the clusterer. */ MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) { var i, r; var removed = false; for (i = 0; i < markers.length; i++) { r = this.removeMarker_(markers[i]); removed = removed || r; } if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ MarkerClusterer.prototype.removeMarker_ = function (marker) { var i; var index = -1; if (this.markers_.indexOf) { index = this.markers_.indexOf(marker); } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { index = i; break; } } } if (index === -1) { // Marker is not in our list of markers, so do nothing: return false; } marker.setMap(null); this.markers_.splice(index, 1); // Remove the marker from the list of managed markers return true; }; /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ MarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = []; }; /** * Recalculates and redraws all the marker clusters from scratch. * Call this after changing any properties. */ MarkerClusterer.prototype.repaint = function () { var oldClusters = this.clusters_.slice(); this.clusters_ = []; this.resetViewport_(false); this.redraw_(); // Remove the old clusters. // Do it in a timeout to prevent blinking effect. setTimeout(function () { var i; for (i = 0; i < oldClusters.length; i++) { oldClusters[i].remove(); } }, 0); }; /** * Returns the current bounds extended by the grid size. * * @param {google.maps.LatLngBounds} bounds The bounds to extend. * @return {google.maps.LatLngBounds} The extended bounds. * @ignore */ MarkerClusterer.prototype.getExtendedBounds = function (bounds) { var projection = this.getProjection(); // Turn the bounds into latlng. var tr = new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getNorthEast().lng()); var bl = new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng()); // Convert the points to pixels and the extend out by the grid size. var trPix = projection.fromLatLngToDivPixel(tr); trPix.x += this.gridSize_; trPix.y -= this.gridSize_; var blPix = projection.fromLatLngToDivPixel(bl); blPix.x -= this.gridSize_; blPix.y += this.gridSize_; // Convert the pixel points back to LatLng var ne = projection.fromDivPixelToLatLng(trPix); var sw = projection.fromDivPixelToLatLng(blPix); // Extend the bounds to contain the new bounds. bounds.extend(ne); bounds.extend(sw); return bounds; }; /** * Redraws all the clusters. */ MarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ MarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. for (i = 0; i < this.markers_.length; i++) { marker = this.markers_[i]; marker.isAdded = false; if (opt_hide) { marker.setMap(null); } } }; /** * Calculates the distance between two latlng locations in km. * * @param {google.maps.LatLng} p1 The first lat lng point. * @param {google.maps.LatLng} p2 The second lat lng point. * @return {number} The distance between the two points in km. * @see http://www.movable-type.co.uk/scripts/latlong.html */ MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) { var R = 6371; // Radius of the Earth in km var dLat = (p2.lat() - p1.lat()) * Math.PI / 180; var dLon = (p2.lng() - p1.lng()) * Math.PI / 180; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; }; /** * Determines if a marker is contained in a bounds. * * @param {google.maps.Marker} marker The marker to check. * @param {google.maps.LatLngBounds} bounds The bounds to check against. * @return {boolean} True if the marker is in the bounds. */ MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) { return bounds.contains(marker.getPosition()); }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new Cluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ MarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringbegin", this); if (typeof this.timerRefStatic !== "undefined") { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); for (i = iFirst; i < iLast; i++) { marker = this.markers_[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringend", this); } }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ MarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; /** * The default function for determining the label text and style * for a cluster icon. * * @param {Array.<google.maps.nggmap-marker>} markers The array of markers represented by the cluster. * @param {number} numStyles The number of marker styles available. * @return {ClusterIconInfo} The information resource for the cluster. * @constant * @ignore */ MarkerClusterer.CALCULATOR = function (markers, numStyles) { var index = 0; var title = ""; var count = markers.length.toString(); var dv = count; while (dv !== 0) { dv = parseInt(dv / 10, 10); index++; } index = Math.min(index, numStyles); return { text: count, index: index, title: title }; }; /** * The number of markers to process in one batch. * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE = 2000; /** * The number of markers to process in one batch (IE only). * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE_IE = 500; /** * The default root name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m"; /** * The default extension name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_EXTENSION = "png"; /** * The default array of sizes for the marker cluster images. * * @type {Array.<number>} * @constant */ MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90]; if (typeof String.prototype.trim !== 'function') { /** * IE hack since trim() doesn't exist in all browsers * @return {string} The string with removed whitespace */ String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } } ;/** * 1.1.9-patched * @name MarkerWithLabel for V3 * @version 1.1.8 [February 26, 2013] * @author Gary Little (inspired by code from Marc Ridey of Google). * @copyright Copyright 2012 Gary Little [gary at luxcentral.com] * @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3 * <code>google.maps.Marker</code> class. * <p> * MarkerWithLabel allows you to define markers with associated labels. As you would expect, * if the marker is draggable, so too will be the label. In addition, a marker with a label * responds to all mouse events in the same manner as a regular marker. It also fires mouse * events and "property changed" events just as a regular marker would. Version 1.1 adds * support for the raiseOnDrag feature introduced in API V3.3. * <p> * If you drag a marker by its label, you can cancel the drag and return the marker to its * original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker * itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class. */ /*! * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint browser:true */ /*global document,google */ /** * @param {Function} childCtor Child class. * @param {Function} parentCtor Parent class. */ function inherits(childCtor, parentCtor) { /** @constructor */ function tempCtor() {} tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); /** @override */ childCtor.prototype.constructor = childCtor; } /** * This constructor creates a label and associates it with a marker. * It is for the private use of the MarkerWithLabel class. * @constructor * @param {Marker} marker The marker with which the label is to be associated. * @param {string} crossURL The URL of the cross image =. * @param {string} handCursor The URL of the hand cursor. * @private */ function MarkerLabel_(marker, crossURL, handCursorURL) { this.marker_ = marker; this.handCursorURL_ = marker.handCursorURL; this.labelDiv_ = document.createElement("div"); this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;"; // Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil // in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that // events can be captured even if the label is in the shadow of a google.maps.InfoWindow. // Code is included here to ensure the veil is always exactly the same size as the label. this.eventDiv_ = document.createElement("div"); this.eventDiv_.style.cssText = this.labelDiv_.style.cssText; // This is needed for proper behavior on MSIE: this.eventDiv_.setAttribute("onselectstart", "return false;"); this.eventDiv_.setAttribute("ondragstart", "return false;"); // Get the DIV for the "X" to be displayed when the marker is raised. this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL); } inherits(MarkerLabel_, google.maps.OverlayView); /** * Returns the DIV for the cross used when dragging a marker when the * raiseOnDrag parameter set to true. One cross is shared with all markers. * @param {string} crossURL The URL of the cross image =. * @private */ MarkerLabel_.getSharedCross = function (crossURL) { var div; if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") { div = document.createElement("img"); div.style.cssText = "position: absolute; z-index: 1000002; display: none;"; // Hopefully Google never changes the standard "X" attributes: div.style.marginLeft = "-8px"; div.style.marginTop = "-9px"; div.src = crossURL; MarkerLabel_.getSharedCross.crossDiv = div; } return MarkerLabel_.getSharedCross.crossDiv; }; /** * Adds the DIV representing the label to the DOM. This method is called * automatically when the marker's <code>setMap</code> method is called. * @private */ MarkerLabel_.prototype.onAdd = function () { var me = this; var cMouseIsDown = false; var cDraggingLabel = false; var cSavedZIndex; var cLatOffset, cLngOffset; var cIgnoreClick; var cRaiseEnabled; var cStartPosition; var cStartCenter; // Constants: var cRaiseOffset = 20; var cDraggingCursor = "url(" + this.handCursorURL_ + ")"; // Stops all processing of an event. // var cAbortEvent = function (e) { if (e.preventDefault) { e.preventDefault(); } e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; var cStopBounce = function () { me.marker_.setAnimation(null); }; this.getPanes().overlayImage.appendChild(this.labelDiv_); this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_); // One cross is shared with all markers, so only add it once: if (typeof MarkerLabel_.getSharedCross.processed === "undefined") { this.getPanes().overlayImage.appendChild(this.crossDiv_); MarkerLabel_.getSharedCross.processed = true; } this.listeners_ = [ google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { this.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseover", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) { if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) { this.style.cursor = me.marker_.getCursor(); google.maps.event.trigger(me.marker_, "mouseout", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) { cDraggingLabel = false; if (me.marker_.getDraggable()) { cMouseIsDown = true; this.style.cursor = cDraggingCursor; } if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "mousedown", e); cAbortEvent(e); // Prevent map pan when starting a drag on a label } }), google.maps.event.addDomListener(document, "mouseup", function (mEvent) { var position; if (cMouseIsDown) { cMouseIsDown = false; me.eventDiv_.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseup", mEvent); } if (cDraggingLabel) { if (cRaiseEnabled) { // Lower the marker & label position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition()); position.y += cRaiseOffset; me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); // This is not the same bouncing style as when the marker portion is dragged, // but it will have to do: try { // Will fail if running Google Maps API earlier than V3.3 me.marker_.setAnimation(google.maps.Animation.BOUNCE); setTimeout(cStopBounce, 1406); } catch (e) {} } me.crossDiv_.style.display = "none"; me.marker_.setZIndex(cSavedZIndex); cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag cDraggingLabel = false; mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragend", mEvent); } }), google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) { var position; if (cMouseIsDown) { if (cDraggingLabel) { // Change the reported location from the mouse position to the marker position: mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset); position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng); if (cRaiseEnabled) { me.crossDiv_.style.left = position.x + "px"; me.crossDiv_.style.top = position.y + "px"; me.crossDiv_.style.display = ""; position.y -= cRaiseOffset; } me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px"; } google.maps.event.trigger(me.marker_, "drag", mEvent); } else { // Calculate offsets from the click point to the marker position: cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat(); cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng(); cSavedZIndex = me.marker_.getZIndex(); cStartPosition = me.marker_.getPosition(); cStartCenter = me.marker_.getMap().getCenter(); cRaiseEnabled = me.marker_.get("raiseOnDrag"); cDraggingLabel = true; me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragstart", mEvent); } } }), google.maps.event.addDomListener(document, "keydown", function (e) { if (cDraggingLabel) { if (e.keyCode === 27) { // Esc key cRaiseEnabled = false; me.marker_.setPosition(cStartPosition); me.marker_.getMap().setCenter(cStartCenter); google.maps.event.trigger(document, "mouseup", e); } } }), google.maps.event.addDomListener(this.eventDiv_, "click", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { if (cIgnoreClick) { // Ignore the click reported when a label drag ends cIgnoreClick = false; } else { google.maps.event.trigger(me.marker_, "click", e); cAbortEvent(e); // Prevent click from being passed on to map } } }), google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "dblclick", e); cAbortEvent(e); // Prevent map zoom when double-clicking on a label } }), google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) { if (!cDraggingLabel) { cRaiseEnabled = this.get("raiseOnDrag"); } }), google.maps.event.addListener(this.marker_, "drag", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(cRaiseOffset); // During a drag, the marker's z-index is temporarily set to 1000000 to // ensure it appears above all other markers. Also set the label's z-index // to 1000000 (plus or minus 1 depending on whether the label is supposed // to be above or below the marker). me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1); } } }), google.maps.event.addListener(this.marker_, "dragend", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(0); // Also restores z-index of label } } }), google.maps.event.addListener(this.marker_, "position_changed", function () { me.setPosition(); }), google.maps.event.addListener(this.marker_, "zindex_changed", function () { me.setZIndex(); }), google.maps.event.addListener(this.marker_, "visible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "labelvisible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "title_changed", function () { me.setTitle(); }), google.maps.event.addListener(this.marker_, "labelcontent_changed", function () { me.setContent(); }), google.maps.event.addListener(this.marker_, "labelanchor_changed", function () { me.setAnchor(); }), google.maps.event.addListener(this.marker_, "labelclass_changed", function () { me.setStyles(); }), google.maps.event.addListener(this.marker_, "labelstyle_changed", function () { me.setStyles(); }) ]; }; /** * Removes the DIV for the label from the DOM. It also removes all event handlers. * This method is called automatically when the marker's <code>setMap(null)</code> * method is called. * @private */ MarkerLabel_.prototype.onRemove = function () { var i; if (this.labelDiv_.parentNode !== null) this.labelDiv_.parentNode.removeChild(this.labelDiv_); if (this.eventDiv_.parentNode !== null) this.eventDiv_.parentNode.removeChild(this.eventDiv_); // Remove event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } }; /** * Draws the label on the map. * @private */ MarkerLabel_.prototype.draw = function () { this.setContent(); this.setTitle(); this.setStyles(); }; /** * Sets the content of the label. * The content can be plain text or an HTML DOM node. * @private */ MarkerLabel_.prototype.setContent = function () { var content = this.marker_.get("labelContent"); if (typeof content.nodeType === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; } else { this.labelDiv_.innerHTML = ""; // Remove current content this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.eventDiv_.appendChild(content); } }; /** * Sets the content of the tool tip for the label. It is * always set to be the same as for the marker itself. * @private */ MarkerLabel_.prototype.setTitle = function () { this.eventDiv_.title = this.marker_.getTitle() || ""; }; /** * Sets the style of the label by setting the style sheet and applying * other specific styles requested. * @private */ MarkerLabel_.prototype.setStyles = function () { var i, labelStyle; // Apply style values from the style sheet defined in the labelClass parameter: this.labelDiv_.className = this.marker_.get("labelClass"); this.eventDiv_.className = this.labelDiv_.className; // Clear existing inline style values: this.labelDiv_.style.cssText = ""; this.eventDiv_.style.cssText = ""; // Apply style values defined in the labelStyle parameter: labelStyle = this.marker_.get("labelStyle"); for (i in labelStyle) { if (labelStyle.hasOwnProperty(i)) { this.labelDiv_.style[i] = labelStyle[i]; this.eventDiv_.style[i] = labelStyle[i]; } } this.setMandatoryStyles(); }; /** * Sets the mandatory styles to the DIV representing the label as well as to the * associated event DIV. This includes setting the DIV position, z-index, and visibility. * @private */ MarkerLabel_.prototype.setMandatoryStyles = function () { this.labelDiv_.style.position = "absolute"; this.labelDiv_.style.overflow = "hidden"; // Make sure the opacity setting causes the desired effect on MSIE: if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") { this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\""; this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")"; } this.eventDiv_.style.position = this.labelDiv_.style.position; this.eventDiv_.style.overflow = this.labelDiv_.style.overflow; this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\""; this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE this.setAnchor(); this.setPosition(); // This also updates z-index, if necessary. this.setVisible(); }; /** * Sets the anchor point of the label. * @private */ MarkerLabel_.prototype.setAnchor = function () { var anchor = this.marker_.get("labelAnchor"); this.labelDiv_.style.marginLeft = -anchor.x + "px"; this.labelDiv_.style.marginTop = -anchor.y + "px"; this.eventDiv_.style.marginLeft = -anchor.x + "px"; this.eventDiv_.style.marginTop = -anchor.y + "px"; }; /** * Sets the position of the label. The z-index is also updated, if necessary. * @private */ MarkerLabel_.prototype.setPosition = function (yOffset) { var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition()); if (typeof yOffset === "undefined") { yOffset = 0; } this.labelDiv_.style.left = Math.round(position.x) + "px"; this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px"; this.eventDiv_.style.left = this.labelDiv_.style.left; this.eventDiv_.style.top = this.labelDiv_.style.top; this.setZIndex(); }; /** * Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index * of the label is set to the vertical coordinate of the label. This is in keeping with the default * stacking order for Google Maps: markers to the south are in front of markers to the north. * @private */ MarkerLabel_.prototype.setZIndex = function () { var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1); if (typeof this.marker_.getZIndex() === "undefined") { this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } else { this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } }; /** * Sets the visibility of the label. The label is visible only if the marker itself is * visible (i.e., its visible property is true) and the labelVisible property is true. * @private */ MarkerLabel_.prototype.setVisible = function () { if (this.marker_.get("labelVisible")) { this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none"; } else { this.labelDiv_.style.display = "none"; } this.eventDiv_.style.display = this.labelDiv_.style.display; }; /** * @name MarkerWithLabelOptions * @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor. * The properties available are the same as for <code>google.maps.Marker</code> with the addition * of the properties listed below. To change any of these additional properties after the labeled * marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>. * <p> * When any of these properties changes, a property changed event is fired. The names of these * events are derived from the name of the property and are of the form <code>propertyname_changed</code>. * For example, if the content of the label changes, a <code>labelcontent_changed</code> event * is fired. * <p> * @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node). * @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so * that its top left corner is positioned at the anchor point of the associated marker. Use this * property to change the anchor point of the label. For example, to center a 50px-wide label * beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>. * (Note: x-values increase to the right and y-values increase to the top.) * @property {string} [labelClass] The name of the CSS class defining the styles for the label. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {Object} [labelStyle] An object literal whose properties define specific CSS * style values to be applied to the label. Style values defined here override those that may * be defined in the <code>labelClass</code> style sheet. If this property is changed after the * label has been created, all previously set styles (except those defined in the style sheet) * are removed from the label before the new style values are applied. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its * associated marker should appear in the background (i.e., in a plane below the marker). * The default is <code>false</code>, which causes the label to appear in the foreground. * @property {boolean} [labelVisible] A flag indicating whether the label is to be visible. * The default is <code>true</code>. Note that even if <code>labelVisible</code> is * <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also * visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>). * @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be * raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is * being created and a version of Google Maps API earlier than V3.3 is being used, this property * must be set to <code>false</code>. * @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the * marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel, * so the value of this parameter is always forced to <code>false</code>. * @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"] * The URL of the cross image to be displayed while dragging a marker. * @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"] * The URL of the cursor to be displayed while dragging a marker. */ /** * Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}. * @constructor * @param {MarkerWithLabelOptions} [opt_options] The optional parameters. */ function MarkerWithLabel(opt_options) { opt_options = opt_options || {}; opt_options.labelContent = opt_options.labelContent || ""; opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0); opt_options.labelClass = opt_options.labelClass || "markerLabels"; opt_options.labelStyle = opt_options.labelStyle || {}; opt_options.labelInBackground = opt_options.labelInBackground || false; if (typeof opt_options.labelVisible === "undefined") { opt_options.labelVisible = true; } if (typeof opt_options.raiseOnDrag === "undefined") { opt_options.raiseOnDrag = true; } if (typeof opt_options.clickable === "undefined") { opt_options.clickable = true; } if (typeof opt_options.draggable === "undefined") { opt_options.draggable = false; } if (typeof opt_options.optimized === "undefined") { opt_options.optimized = false; } opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; opt_options.optimized = false; // Optimized rendering is not supported this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker // Call the parent constructor. It calls Marker.setValues to initialize, so all // the new parameters are conveniently saved and can be accessed with get/set. // Marker.set triggers a property changed event (called "propertyname_changed") // that the marker label listens for in order to react to state changes. google.maps.Marker.apply(this, arguments); } inherits(MarkerWithLabel, google.maps.Marker); /** * Overrides the standard Marker setMap function. * @param {Map} theMap The map to which the marker is to be added. * @private */ MarkerWithLabel.prototype.setMap = function (theMap) { // Call the inherited function... google.maps.Marker.prototype.setMap.apply(this, arguments); // ... then deal with the label: this.label.setMap(theMap); }; //END REPLACE window.InfoBox = InfoBox; window.Cluster = Cluster; window.ClusterIcon = ClusterIcon; window.MarkerClusterer = MarkerClusterer; window.MarkerLabel_ = MarkerLabel_; window.MarkerWithLabel = MarkerWithLabel; }) }; });;/** * Performance overrides on MarkerClusterer custom to Angular Google Maps * * Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14. */ angular.module('google-maps.extensions'.ns()).service('ExtendMarkerClusterer'.ns(), function () { return { init: _.once(function () { (function () { var __hasProp = {}.hasOwnProperty, __extends = function (child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; window.NgMapCluster = (function (_super) { __extends(NgMapCluster, _super); function NgMapCluster(opts) { NgMapCluster.__super__.constructor.call(this, opts); this.markers_ = new window.PropMap(); } /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ NgMapCluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { var oldMarker = this.markers_.get(marker.key); if (oldMarker.getPosition().lat() == marker.getPosition().lat() && oldMarker.getPosition().lon() == marker.getPosition().lon()) //if nothing has changed return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. this.markers_.values().forEach(function (m) { m.setMap(null); }); } else { marker.setMap(null); } // this.updateIcon_(); return true; }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ NgMapCluster.prototype.isMarkerAlreadyAdded_ = function (marker) { return _.isNullOrUndefined(this.markers_.get(marker.key)); }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ NgMapCluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); var markers = this.getMarkers().values(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } return bounds; }; /** * Removes the cluster from the map. * * @ignore */ NgMapCluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = new PropMap(); delete this.markers_; }; return NgMapCluster; })(Cluster); window.NgMapMarkerClusterer = (function (_super) { __extends(NgMapMarkerClusterer, _super); function NgMapMarkerClusterer(map, opt_markers, opt_options) { NgMapMarkerClusterer.__super__.constructor.call(this, map, opt_markers, opt_options); this.markers_ = new window.PropMap(); } /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ NgMapMarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = new PropMap(); }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ NgMapMarkerClusterer.prototype.removeMarker_ = function (marker) { if (!this.markers_.get(marker.key)) { return false; } marker.setMap(null); this.markers_.remove(marker.key); // Remove the marker from the list of managed markers return true; }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ NgMapMarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringbegin", this); if (typeof this.timerRefStatic !== "undefined") { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); for (i = iFirst; i < iLast; i++) { marker = this.markers_.values()[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { // custom addition by ngmaps // update icon for all clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].updateIcon_(); } delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringend", this); } }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ NgMapMarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new NgMapCluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Redraws all the clusters. */ NgMapMarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ NgMapMarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. this.markers_.values().forEach(function (marker) { marker.isAdded = false; if (opt_hide) { marker.setMap(null); } }); }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ NgMapMarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { if (property !== 'constructor') this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; NgMapMarkerClusterer.prototype.onAdd = function() { var cMarkerClusterer = this; this.activeMap_ = this.getMap(); this.ready_ = true; this.repaint(); // Add the map event listeners this.listeners_ = [ google.maps.event.addListener(this.getMap(), "zoom_changed", function () { cMarkerClusterer.resetViewport_(false); // Workaround for this Google bug: when map is at level 0 and "-" of // zoom slider is clicked, a "zoom_changed" event is fired even though // the map doesn't zoom out any further. In this situation, no "idle" // event is triggered so the cluster markers that have been removed // do not get redrawn. Same goes for a zoom in at maxZoom. if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) { google.maps.event.trigger(this, "idle"); } }) ]; }; return NgMapMarkerClusterer; })(MarkerClusterer); }).call(this); }) }; });
src/mui/input/NullableBooleanInput.js
RestUI/rest-ui
import React from 'react'; import PropTypes from 'prop-types'; import SelectInput from './SelectInput'; import { translate } from '../../i18n'; export const NullableBooleanInput = ({ input, meta: { touched, error }, label, source, elStyle, resource, translate }) => ( <SelectInput input={input} label={label} source={source} resource={resource} choices={[ { id: null, name: '' }, { id: false, name: translate('aor.boolean.false') }, { id: true, name: translate('aor.boolean.true') }, ]} errorText={touched && error} style={elStyle} /> ); NullableBooleanInput.propTypes = { addField: PropTypes.bool.isRequired, elStyle: PropTypes.object, input: PropTypes.object, label: PropTypes.string, meta: PropTypes.object, resource: PropTypes.string, source: PropTypes.string, translate: PropTypes.func.isRequired, }; NullableBooleanInput.defaultProps = { addField: true, }; export default translate(NullableBooleanInput);
src/svg-icons/image/burst-mode.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBurstMode = (props) => ( <SvgIcon {...props}> <path d="M1 5h2v14H1zm4 0h2v14H5zm17 0H10c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zM11 17l2.5-3.15L15.29 16l2.5-3.22L21 17H11z"/> </SvgIcon> ); ImageBurstMode = pure(ImageBurstMode); ImageBurstMode.displayName = 'ImageBurstMode'; ImageBurstMode.muiName = 'SvgIcon'; export default ImageBurstMode;
src/components/icons/ChevronUpIcon.js
InsideSalesOfficial/insidesales-components
import React from 'react'; const ChevronUpIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 100 100"> {props.title && <title>{props.title}</title>} <polygon points="28.79 67.68 50 46.46 71.21 67.68 78.28 60.61 50 32.32 21.72 60.61 28.79 67.68" /> </svg> ); export default ChevronUpIcon;
website/irulez/src/components/Login.js
deklungel/iRulez
import React, { Component } from 'react'; import './Login.css'; import AuthService from './AuthService'; class Login extends Component { constructor() { super(); this.handleChange = this.handleChange.bind(this); this.handleFormSubmit = this.handleFormSubmit.bind(this); this.Auth = new AuthService(); } componentWillMount() { if (this.Auth.loggedIn()) this.props.history.replace('/'); } render() { return ( <div className='center'> <div className='card'> <h1>Login</h1> <form onSubmit={this.handleFormSubmit}> <input required className='form-item' placeholder='Username goes here...' name='username' type='email' onChange={this.handleChange} /> <input required className='form-item' placeholder='Password goes here...' name='password' type='password' onChange={this.handleChange} /> <input className='form-submit' value='SUBMIT' type='submit' /> </form> </div> </div> ); } handleChange(e) { this.setState({ [e.target.name]: e.target.value }); } handleFormSubmit(e) { e.preventDefault(); this.Auth.login(this.state.username, this.state.password) .then(res => { if (this.Auth.getProfile().admin) { this.props.history.replace('/administrator'); } else { this.props.history.replace('/'); } }) .catch(err => { alert(err); }); } } export default Login;
blueocean-material-icons/src/js/components/svg-icons/content/clear.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ContentClear = (props) => ( <SvgIcon {...props}> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/> </SvgIcon> ); ContentClear.displayName = 'ContentClear'; ContentClear.muiName = 'SvgIcon'; export default ContentClear;
WebRoot/plugin/jquery-scrollup/js/lib/jquery-1.9.1.min.js
panxiaochao/BPMIS
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
javascripts/jquery-1.10.2.min.js
nakamuraapp/nakamuraapp.github.io
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery-1.10.2.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
blueprints/dumb/files/__root__/components/__name__/__name__.js
bhoomit/formula-editor
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
src/docs/examples/TextInput/ExampleOptional.js
tlraridon/ps-react-train-tlr
import React from 'react'; import TextInput from 'ps-react-train-tlr/TextInput'; /** Optional Textbox */ export default class ExampleOptional extends React.Component { render() { return ( <TextInput htmlId="excample-optional" label="First Name" name="firstname" placeholder="First Name" onChange={() => {}} /> ) } }
src/components/NotFoundPage.js
dvwzj-smcl/schedule
import React from 'react'; import { Link } from 'react-router'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
packages/bonde-styleguide/src/content/Icon/svg/DoubleArrowLeft.js
ourcities/rebu-client
import React from 'react' const Icon = ({ className, color, size }) => ( <svg className={className} width={size || '16'} height={size || '13'} viewBox='0 0 16 13' xmlns='http://www.w3.org/2000/svg' > <g fill='none' fillRule='evenodd'> <g transform='translate(-1116 -11655)' fill={color} stroke={color}> <g transform='translate(1116 11655)'> <g strokeWidth='0.5' fillRule='nonzero'> <polygon fill={color} transform='matrix(0 -1 -1 0 10.767 10.767)' points='4.26666667 7.70352667 8.82598417 2.83810732 9.97568098 4.06499206 5.41636347 8.93041142 4.27097401 10.1618927 3.11266252 8.93500794 -1.44234765 4.06499206 -0.292650842 2.83810732' /> <polygon fill={color} transform='matrix(0 -1 -1 0 18.767 18.767)' points='12.2666667 7.70352667 16.8259842 2.83810732 17.975681 4.06499206 13.4163635 8.93041142 12.270974 10.1618927 11.1126625 8.93500794 6.55765235 4.06499206 7.70734916 2.83810732' /> </g> </g> </g> </g> </svg> ) Icon.displayName = 'Icon.DoubleArrowLeft' export default Icon
quiz.js
qiwenmin/HamExam
import React, { Component } from 'react'; import { Alert, StyleSheet, TouchableHighlight, Text, Image, View, ScrollView } from 'react-native'; import NavigationBar from 'react-native-navbar'; import _ from 'lodash'; import Libs from './libs'; import quizImgs from './quizimgs'; import studyRecord from './studyrecord'; function getExamIdx(quizIdx, count) { var result = new Set(); while (result.size < count) { var ri = Math.floor(Math.random() * quizIdx.length); result.add(quizIdx[ri]); } return [...result]; } export default class Quiz extends Component { constructor(props) { super(props); if (props.context.libType == 'wrong') { this.quizIdx = [...props.context.record.wrong]; this.quizTotal = this.quizIdx.length; } else if (props.context.libType == 'exam') { this.quizIdx = getExamIdx(Libs[props.context.level].idx, Libs[props.context.level].quizCount); this.quizTotal = this.quizIdx.length; this.passCount = Libs[props.context.level].passCount; } else { this.quizIdx = Libs[props.context.level].idx; this.quizTotal = Libs[props.context.level].total; } this.quizLib = Libs.all.lib; this.answers = null; this.selectedAnswer = null; this.state = { quizIndex: props.context.libType == 'wrong' ? props.context.record.wrongQuizIndex : props.context.record.quizIndex, selectedAnswer: null }; if (props.context.libType == 'exam') { this.state.quizIndex = 0; this.tested = new Set(); this.wrong = new Set(); } } setQuizIndex(idx) { if (idx < 0) { idx = 0; } else if (idx >= this.quizTotal) { idx = this.quizTotal - 1; } if (idx != this.state.quizIndex) { this.answers = null; if (this.props.context.libType == 'wrong') { this.props.context.record.wrongQuizIndex = idx; } else if (this.props.context.libType == 'study'){ this.props.context.record.quizIndex = idx; } if (this.props.context.libType != 'exam') { studyRecord.save(this.props.context.level, this.props.context.record); } this.setState({ quizIndex: idx, selectedAnswer: null }); } } pressFirst() { this.setQuizIndex(0); } pressPrev() { this.setQuizIndex(this.state.quizIndex - 1); } pressNext() { this.setQuizIndex(this.state.quizIndex + 1); } pressLast() { this.setQuizIndex(this.quizTotal - 1); } selectAnswer(idx) { var isWrong = (this.answers[idx] != 'a'); var quizId = this.quizIdx[this.state.quizIndex]; if (isWrong) { this.props.context.record.wrong.add(quizId); } if (this.props.context.libType == 'exam') { if (isWrong && (!this.tested.has(quizId))) { this.wrong.add(quizId); } this.tested.add(quizId); } else { this.props.context.record.studied.add(quizId); } studyRecord.save(this.props.context.level, this.props.context.record); this.selectedAnswer = idx; this.setState({ quizIndex: this.state.quizIndex, selectedAnswer: idx }); if (this.props.context.libType == 'exam') { if (this.tested.size == this.quizTotal) { var correctCount = this.quizTotal - this.wrong.size; var passed = '考过了~👍'; if (correctCount < this.passCount) { passed = '没考过~👎\n得答对' + this.passCount + '题才能通过呢。'; } Alert.alert('测试完成!共答' + this.quizTotal + '题、答错' + this.wrong.size + '题。' + passed); } } } render() { let level = this.props.context.level; let quiz = this.quizLib[this.quizIdx[this.state.quizIndex]]; let record = this.props.context.record; if (this.answers == null) { this.answers = _.shuffle(['a', 'b', 'c', 'd']); } var answerStyles = { 'a': {}, 'b': {}, 'c': {}, 'd': {} }; if (this.state.selectedAnswer != null) { answerStyles[this.answers[this.state.selectedAnswer]] = { backgroundColor: 'lightcoral' }; answerStyles['a'] = { backgroundColor: 'lightgreen' }; } var title = ''; if (this.props.context.libType == 'study') { title = '学习题库'; } else if (this.props.context.libType == 'wrong') { title = '练习错题'; } else if (this.props.context.libType == 'exam') { title = '模拟考试'; } var progressInfo = " 已学:" + record.studied.size + " | 错题:" + record.wrong.size; var progressColor = "black"; if (this.props.context.libType == 'exam') { var passRate = this.passCount / this.quizTotal; var rateString = " - / " + Math.round(passRate * 10000) / 100 + "%"; if (this.tested.size > 0) { var currentPassRate = (this.tested.size - this.wrong.size) / this.tested.size; progressColor = (currentPassRate >= passRate) ? "green" : "red"; rateString = Math.round(currentPassRate * 10000) / 100 + "% / " + Math.round(passRate * 10000) / 100 + "%"; } progressInfo = " 已测:" + this.tested.size + " | 答错:" + this.wrong.size + "\n正确率:" + rateString; } var quizImg = (<View/>); if (quiz.p != null) { var imgSrc = quizImgs[quiz.p]; quizImg = ( <View style={{justifyContent: 'center', alignItems: 'center'}}> <Image style={{height: 180}} resizeMode="contain" source={imgSrc}/> </View> ); } return ( <View style={styles.container}> <NavigationBar title={{ title: Libs[this.props.context.level].name + title, style: styles.title }} leftButton={{ title: '<返回', handler: this.props.navigator.pop }} /> <Text style={{textAlign: "center", fontSize: 12, margin: 2, color: progressColor}}> {this.state.quizIndex + 1}/{this.quizTotal} | {progressInfo} </Text> <ScrollView style={{}}> <Text style={styles.q}> {quiz.q} </Text> {quizImg} <View style={{}}> <TouchableHighlight style={answerStyles[this.answers[0]]} underlayColor='#eee' onPress={() => this.selectAnswer(0)}> <Text style={styles.a}> A、{quiz[this.answers[0]]} </Text> </TouchableHighlight> <TouchableHighlight style={answerStyles[this.answers[1]]} underlayColor='#eee' onPress={() => this.selectAnswer(1)}> <Text style={styles.a}> B、{quiz[this.answers[1]]} </Text> </TouchableHighlight> <TouchableHighlight style={answerStyles[this.answers[2]]} underlayColor='#eee' onPress={() => this.selectAnswer(2)}> <Text style={styles.a}> C、{quiz[this.answers[2]]} </Text> </TouchableHighlight> <TouchableHighlight style={answerStyles[this.answers[3]]} underlayColor='#eee' onPress={() => this.selectAnswer(3)}> <Text style={styles.a}> D、{quiz[this.answers[3]]} </Text> </TouchableHighlight> </View> </ScrollView> <View flexDirection="row" style={{alignItems: "center"}}> <TouchableHighlight underlayColor='#eee' onPress={() => this.pressFirst()}> <Text style={styles.buttonText}> {'<<'}开头 </Text> </TouchableHighlight> <TouchableHighlight underlayColor='#eee' style={{flex: 1}} onPress={() => this.pressPrev()}> <Text style={styles.buttonText}> {'<'}上一题 </Text> </TouchableHighlight> <TouchableHighlight underlayColor='#eee' style={{flex: 1}} onPress={() => this.pressNext()}> <Text style={styles.buttonText}> 下一题{'>'} </Text> </TouchableHighlight> <TouchableHighlight underlayColor='#eee' onPress={() => this.pressLast()}> <Text style={styles.buttonText}> 末尾{'>>'} </Text> </TouchableHighlight> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, padding: 10, backgroundColor: '#fff', }, title: { color: '#000', fontSize: 20, fontWeight: 'bold', }, q: { color: '#000', fontSize: 16, fontWeight: 'bold', textAlign: 'left', margin: 10, }, a: { color: '#000', fontSize: 16, textAlign: 'left', margin: 5, }, buttonText: { color: '#000', textAlign: 'center', margin: 10, }, });
public/assets/js/node_modules/babel-core/lib/transformation/transformers/validation/react.js
ngocson8b/6jar
"use strict"; exports.__esModule = true; // istanbul ignore next function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _messages = require("../../../messages"); var messages = _interopRequireWildcard(_messages); var _types = require("../../../types"); var t = _interopRequireWildcard(_types); // check if the input Literal `source` is an alternate casing of "react" function check(source, file) { if (t.isLiteral(source)) { var name = source.value; var lower = name.toLowerCase(); if (lower === "react" && name !== lower) { throw file.errorWithNode(source, messages.get("didYouMean", "react")); } } } /** * [Please add a description.] */ var visitor = { /** * [Please add a description.] */ CallExpression: function CallExpression(node, parent, scope, file) { if (this.get("callee").isIdentifier({ name: "require" }) && node.arguments.length === 1) { check(node.arguments[0], file); } }, /** * [Please add a description.] */ ModuleDeclaration: function ModuleDeclaration(node, parent, scope, file) { check(node.source, file); } }; exports.visitor = visitor;
app/containers/NotFoundPage/index.js
MaleSharker/Qingyan
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import H1 from 'components/H1'; import messages from './messages'; export default function NotFound() { return ( <article> <H1> <FormattedMessage {...messages.header} /> </H1> </article> ); }
ajax/libs/angular-data/1.5.1/angular-data.js
AlexisArce/cdnjs
/** * @author Jason Dobry <[email protected]> * @file angular-data.js * @version 1.5.1 - Homepage <http://angular-data.pseudobry.com/> * @copyright (c) 2014 Jason Dobry <https://github.com/jmdobry/> * @license MIT <https://github.com/jmdobry/angular-data/blob/master/LICENSE> * * @overview Data store for Angular.js. */ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Modifications // Copyright 2014 Jason Dobry // // Summary of modifications: // Fixed use of "delete" keyword for IE8 compatibility // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { 'use strict'; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); function detectEval() { // Don't test for eval if we're running in a Chrome App environment. // We check for APIs set that only exist in a Chrome App context. if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) { return false; } try { var f = new Function('', 'return true;'); return f(); } catch (ex) { return false; } } var hasEval = detectEval(); var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function diffObjectFromOldObject(object, oldObject) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (newValue !== undefined && newValue === oldObject[prop]) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ var eomObj = { pingPong: true }; var eomRunScheduled = false; Object.observe(eomObj, function() { runEOMTasks(); eomRunScheduled = false; }); return function(fn) { eomTasks.push(fn); if (!eomRunScheduled) { eomRunScheduled = true; eomObj.pingPong = !eomObj.pingPong; } }; })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } /* * The observedSet abstraction is a perf optimization which reduces the total * number of Object.observe observations of a set of objects. The idea is that * groups of Observers will have some object dependencies in common and this * observed set ensures that each object in the transitive closure of * dependencies is only observed once. The observedSet acts as a write barrier * such that whenever any change comes through, all Observers are checked for * changed values. * * Note that this optimization is explicitly moving work from setup-time to * change-time. * * TODO(rafaelw): Implement "garbage collection". In order to move work off * the critical path, when Observers are closed, their observed objects are * not Object.unobserve(d). As a result, it's possible that if the observedSet * is kept open, but some Observers have been closed, it could cause "leaks" * (prevent otherwise collectable objects from being collected). At some * point, we should implement incremental "gc" which keeps a list of * observedSets which may need clean-up and does small amounts of cleanup on a * timeout until all is clean. */ function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; var hasDebugForceFullDelivery = hasObserve && hasEval && (function() { try { eval('%RunMicrotasks()'); return true; } catch (ex) { return false; } })(); global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (hasDebugForceFullDelivery) { eval('%RunMicrotasks()'); return; } if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); var observerSentinel = {}; var expectedRecordTypes = { add: true, update: true, 'delete': true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } global.Observer = Observer; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.ObjectObserver = ObjectObserver; })((exports.Number = { isNaN: window.isNaN }) ? exports : exports); },{}],2:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; },{"./indexOf":7}],3:[function(require,module,exports){ var makeIterator = require('../function/makeIterator_'); /** * Array filter */ function filter(arr, callback, thisObj) { callback = makeIterator(callback, thisObj); var results = []; if (arr == null) { return results; } var i = -1, len = arr.length, value; while (++i < len) { value = arr[i]; if (callback(value, i, arr)) { results.push(value); } } return results; } module.exports = filter; },{"../function/makeIterator_":14}],4:[function(require,module,exports){ var findIndex = require('./findIndex'); /** * Returns first item that matches criteria */ function find(arr, iterator, thisObj){ var idx = findIndex(arr, iterator, thisObj); return idx >= 0? arr[idx] : void(0); } module.exports = find; },{"./findIndex":5}],5:[function(require,module,exports){ var makeIterator = require('../function/makeIterator_'); /** * Returns the index of the first item that matches criteria */ function findIndex(arr, iterator, thisObj){ iterator = makeIterator(iterator, thisObj); if (arr == null) { return -1; } var i = -1, len = arr.length; while (++i < len) { if (iterator(arr[i], i, arr)) { return i; } } return -1; } module.exports = findIndex; },{"../function/makeIterator_":14}],6:[function(require,module,exports){ /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; },{}],7:[function(require,module,exports){ /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; },{}],8:[function(require,module,exports){ var filter = require('./filter'); function isValidString(val) { return (val != null && val !== ''); } /** * Joins strings with the specified separator inserted between each value. * Null values and empty strings will be excluded. */ function join(items, separator) { separator = separator || ''; return filter(items, isValidString).join(separator); } module.exports = join; },{"./filter":3}],9:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * Remove a single item from the array. * (it won't remove duplicates, just a single item) */ function remove(arr, item){ var idx = indexOf(arr, item); if (idx !== -1) arr.splice(idx, 1); } module.exports = remove; },{"./indexOf":7}],10:[function(require,module,exports){ /** * Create slice of source array or array-like object */ function slice(arr, start, end){ var len = arr.length; if (start == null) { start = 0; } else if (start < 0) { start = Math.max(len + start, 0); } else { start = Math.min(start, len); } if (end == null) { end = len; } else if (end < 0) { end = Math.max(len + end, 0); } else { end = Math.min(end, len); } var result = []; while (start < end) { result.push(arr[start++]); } return result; } module.exports = slice; },{}],11:[function(require,module,exports){ /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; },{}],12:[function(require,module,exports){ var isFunction = require('../lang/isFunction'); /** * Creates an object that holds a lookup for the objects in the array. */ function toLookup(arr, key) { var result = {}; if (arr == null) { return result; } var i = -1, len = arr.length, value; if (isFunction(key)) { while (++i < len) { value = arr[i]; result[key(value)] = value; } } else { while (++i < len) { value = arr[i]; result[value[key]] = value; } } return result; } module.exports = toLookup; },{"../lang/isFunction":21}],13:[function(require,module,exports){ /** * Returns the first argument provided to it. */ function identity(val){ return val; } module.exports = identity; },{}],14:[function(require,module,exports){ var identity = require('./identity'); var prop = require('./prop'); var deepMatches = require('../object/deepMatches'); /** * Converts argument into a valid iterator. * Used internally on most array/object/collection methods that receives a * callback/iterator providing a shortcut syntax. */ function makeIterator(src, thisObj){ if (src == null) { return identity; } switch(typeof src) { case 'function': // function is the first to improve perf (most common case) // also avoid using `Function#call` if not needed, which boosts // perf a lot in some cases return (typeof thisObj !== 'undefined')? function(val, i, arr){ return src.call(thisObj, val, i, arr); } : src; case 'object': return function(val){ return deepMatches(val, src); }; case 'string': case 'number': return prop(src); } } module.exports = makeIterator; },{"../object/deepMatches":30,"./identity":13,"./prop":15}],15:[function(require,module,exports){ /** * Returns a function that gets a property of the passed object */ function prop(name){ return function(obj){ return obj[name]; }; } module.exports = prop; },{}],16:[function(require,module,exports){ var kindOf = require('./kindOf'); var isPlainObject = require('./isPlainObject'); var mixIn = require('../object/mixIn'); /** * Clone native types. */ function clone(val){ switch (kindOf(val)) { case 'Object': return cloneObject(val); case 'Array': return cloneArray(val); case 'RegExp': return cloneRegExp(val); case 'Date': return cloneDate(val); default: return val; } } function cloneObject(source) { if (isPlainObject(source)) { return mixIn({}, source); } else { return source; } } function cloneRegExp(r) { var flags = ''; flags += r.multiline ? 'm' : ''; flags += r.global ? 'g' : ''; flags += r.ignoreCase ? 'i' : ''; return new RegExp(r.source, flags); } function cloneDate(date) { return new Date(+date); } function cloneArray(arr) { return arr.slice(); } module.exports = clone; },{"../object/mixIn":37,"./isPlainObject":24,"./kindOf":26}],17:[function(require,module,exports){ var clone = require('./clone'); var forOwn = require('../object/forOwn'); var kindOf = require('./kindOf'); var isPlainObject = require('./isPlainObject'); /** * Recursively clone native types. */ function deepClone(val, instanceClone) { switch ( kindOf(val) ) { case 'Object': return cloneObject(val, instanceClone); case 'Array': return cloneArray(val, instanceClone); default: return clone(val); } } function cloneObject(source, instanceClone) { if (isPlainObject(source)) { var out = {}; forOwn(source, function(val, key) { this[key] = deepClone(val, instanceClone); }, out); return out; } else if (instanceClone) { return instanceClone(source); } else { return source; } } function cloneArray(arr, instanceClone) { var out = [], i = -1, n = arr.length, val; while (++i < n) { out[i] = deepClone(arr[i], instanceClone); } return out; } module.exports = deepClone; },{"../object/forOwn":33,"./clone":16,"./isPlainObject":24,"./kindOf":26}],18:[function(require,module,exports){ var isKind = require('./isKind'); /** */ var isArray = Array.isArray || function (val) { return isKind(val, 'Array'); }; module.exports = isArray; },{"./isKind":22}],19:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isBoolean(val) { return isKind(val, 'Boolean'); } module.exports = isBoolean; },{"./isKind":22}],20:[function(require,module,exports){ var forOwn = require('../object/forOwn'); var isArray = require('./isArray'); function isEmpty(val){ if (val == null) { // typeof null == 'object' so we check it first return true; } else if ( typeof val === 'string' || isArray(val) ) { return !val.length; } else if ( typeof val === 'object' ) { var result = true; forOwn(val, function(){ result = false; return false; // break loop }); return result; } else { return true; } } module.exports = isEmpty; },{"../object/forOwn":33,"./isArray":18}],21:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isFunction(val) { return isKind(val, 'Function'); } module.exports = isFunction; },{"./isKind":22}],22:[function(require,module,exports){ var kindOf = require('./kindOf'); /** * Check if value is from a specific "kind". */ function isKind(val, kind){ return kindOf(val) === kind; } module.exports = isKind; },{"./kindOf":26}],23:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isObject(val) { return isKind(val, 'Object'); } module.exports = isObject; },{"./isKind":22}],24:[function(require,module,exports){ /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; },{}],25:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isRegExp(val) { return isKind(val, 'RegExp'); } module.exports = isRegExp; },{"./isKind":22}],26:[function(require,module,exports){ var _rKind = /^\[object (.*)\]$/, _toString = Object.prototype.toString, UNDEF; /** * Gets the "kind" of value. (e.g. "String", "Number", etc) */ function kindOf(val) { if (val === null) { return 'Null'; } else if (val === UNDEF) { return 'Undefined'; } else { return _rKind.exec( _toString.call(val) )[1]; } } module.exports = kindOf; },{}],27:[function(require,module,exports){ /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; },{}],28:[function(require,module,exports){ /** * @constant Maximum 32-bit signed integer value. (2^31 - 1) */ module.exports = 2147483647; },{}],29:[function(require,module,exports){ /** * @constant Minimum 32-bit signed integer value (-2^31). */ module.exports = -2147483648; },{}],30:[function(require,module,exports){ var forOwn = require('./forOwn'); var isArray = require('../lang/isArray'); function containsMatch(array, pattern) { var i = -1, length = array.length; while (++i < length) { if (deepMatches(array[i], pattern)) { return true; } } return false; } function matchArray(target, pattern) { var i = -1, patternLength = pattern.length; while (++i < patternLength) { if (!containsMatch(target, pattern[i])) { return false; } } return true; } function matchObject(target, pattern) { var result = true; forOwn(pattern, function(val, key) { if (!deepMatches(target[key], val)) { // Return false to break out of forOwn early return (result = false); } }); return result; } /** * Recursively check if the objects match. */ function deepMatches(target, pattern){ if (target && typeof target === 'object') { if (isArray(target) && isArray(pattern)) { return matchArray(target, pattern); } else { return matchObject(target, pattern); } } else { return target === pattern; } } module.exports = deepMatches; },{"../lang/isArray":18,"./forOwn":33}],31:[function(require,module,exports){ var forOwn = require('./forOwn'); var isPlainObject = require('../lang/isPlainObject'); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; },{"../lang/isPlainObject":24,"./forOwn":33}],32:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { var ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype; while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; },{"./hasOwn":34}],33:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var forIn = require('./forIn'); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; },{"./forIn":32,"./hasOwn":34}],34:[function(require,module,exports){ /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; },{}],35:[function(require,module,exports){ var forOwn = require('./forOwn'); /** * Get object keys */ var keys = Object.keys || function (obj) { var keys = []; forOwn(obj, function(val, key){ keys.push(key); }); return keys; }; module.exports = keys; },{"./forOwn":33}],36:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var deepClone = require('../lang/deepClone'); var isObject = require('../lang/isObject'); /** * Deep merge objects. */ function merge() { var i = 1, key, val, obj, target; // make sure we don't modify source element and it's properties // objects are passed by reference target = deepClone( arguments[0] ); while (obj = arguments[i++]) { for (key in obj) { if ( ! hasOwn(obj, key) ) { continue; } val = obj[key]; if ( isObject(val) && isObject(target[key]) ){ // inception, deep merge objects target[key] = merge(target[key], val); } else { // make sure arrays, regexp, date, objects are cloned target[key] = deepClone(val); } } } return target; } module.exports = merge; },{"../lang/deepClone":17,"../lang/isObject":23,"./hasOwn":34}],37:[function(require,module,exports){ var forOwn = require('./forOwn'); /** * Combine properties from all the objects into first one. * - This method affects target object in place, if you want to create a new Object pass an empty object as first param. * @param {object} target Target Object * @param {...object} objects Objects to be combined (0...n objects). * @return {object} Target Object. */ function mixIn(target, objects){ var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj != null) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key){ this[key] = val; } module.exports = mixIn; },{"./forOwn":33}],38:[function(require,module,exports){ var forEach = require('../array/forEach'); /** * Create nested object if non-existent */ function namespace(obj, path){ if (!path) return obj; forEach(path.split('.'), function(key){ if (!obj[key]) { obj[key] = {}; } obj = obj[key]; }); return obj; } module.exports = namespace; },{"../array/forEach":6}],39:[function(require,module,exports){ var slice = require('../array/slice'); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ function pick(obj, var_keys){ var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1), out = {}, i = 0, key; while (key = keys[i++]) { out[key] = obj[key]; } return out; } module.exports = pick; },{"../array/slice":10}],40:[function(require,module,exports){ var namespace = require('./namespace'); /** * set "nested" object property */ function set(obj, prop, val){ var parts = (/^(.+)\.(.+)$/).exec(prop); if (parts){ namespace(obj, parts[1])[parts[2]] = val; } else { obj[prop] = val; } } module.exports = set; },{"./namespace":38}],41:[function(require,module,exports){ var randInt = require('./randInt'); var isArray = require('../lang/isArray'); /** * Returns a random element from the supplied arguments * or from the array (if single argument is an array). */ function choice(items) { var target = (arguments.length === 1 && isArray(items))? items : arguments; return target[ randInt(0, target.length - 1) ]; } module.exports = choice; },{"../lang/isArray":18,"./randInt":45}],42:[function(require,module,exports){ var randHex = require('./randHex'); var choice = require('./choice'); /** * Returns pseudo-random guid (UUID v4) * IMPORTANT: it's not totally "safe" since randHex/choice uses Math.random * by default and sequences can be predicted in some cases. See the * "random/random" documentation for more info about it and how to replace * the default PRNG. */ function guid() { return ( randHex(8)+'-'+ randHex(4)+'-'+ // v4 UUID always contain "4" at this position to specify it was // randomly generated '4' + randHex(3) +'-'+ // v4 UUID always contain chars [a,b,8,9] at this position choice(8, 9, 'a', 'b') + randHex(3)+'-'+ randHex(12) ); } module.exports = guid; },{"./choice":41,"./randHex":44}],43:[function(require,module,exports){ var random = require('./random'); var MIN_INT = require('../number/MIN_INT'); var MAX_INT = require('../number/MAX_INT'); /** * Returns random number inside range */ function rand(min, max){ min = min == null? MIN_INT : min; max = max == null? MAX_INT : max; return min + (max - min) * random(); } module.exports = rand; },{"../number/MAX_INT":28,"../number/MIN_INT":29,"./random":46}],44:[function(require,module,exports){ var choice = require('./choice'); var _chars = '0123456789abcdef'.split(''); /** * Returns a random hexadecimal string */ function randHex(size){ size = size && size > 0? size : 6; var str = ''; while (size--) { str += choice(_chars); } return str; } module.exports = randHex; },{"./choice":41}],45:[function(require,module,exports){ var MIN_INT = require('../number/MIN_INT'); var MAX_INT = require('../number/MAX_INT'); var rand = require('./rand'); /** * Gets random integer inside range or snap to min/max values. */ function randInt(min, max){ min = min == null? MIN_INT : ~~min; max = max == null? MAX_INT : ~~max; // can't be max + 0.5 otherwise it will round up if `rand` // returns `max` causing it to overflow range. // -0.5 and + 0.49 are required to avoid bias caused by rounding return Math.round( rand(min - 0.5, max + 0.499999999999) ); } module.exports = randInt; },{"../number/MAX_INT":28,"../number/MIN_INT":29,"./rand":43}],46:[function(require,module,exports){ /** * Just a wrapper to Math.random. No methods inside mout/random should call * Math.random() directly so we can inject the pseudo-random number * generator if needed (ie. in case we need a seeded random or a better * algorithm than the native one) */ function random(){ return random.get(); } // we expose the method so it can be swapped if needed random.get = Math.random; module.exports = random; },{}],47:[function(require,module,exports){ var toString = require('../lang/toString'); var replaceAccents = require('./replaceAccents'); var removeNonWord = require('./removeNonWord'); var upperCase = require('./upperCase'); var lowerCase = require('./lowerCase'); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; },{"../lang/toString":27,"./lowerCase":48,"./removeNonWord":51,"./replaceAccents":52,"./upperCase":53}],48:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; },{"../lang/toString":27}],49:[function(require,module,exports){ var join = require('../array/join'); var slice = require('../array/slice'); /** * Group arguments as path segments, if any of the args is `null` or an * empty string it will be ignored from resulting path. */ function makePath(var_args){ var result = join(slice(arguments), '/'); // need to disconsider duplicate '/' after protocol (eg: 'http://') return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); } module.exports = makePath; },{"../array/join":8,"../array/slice":10}],50:[function(require,module,exports){ var toString = require('../lang/toString'); var camelCase = require('./camelCase'); var upperCase = require('./upperCase'); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; },{"../lang/toString":27,"./camelCase":47,"./upperCase":53}],51:[function(require,module,exports){ var toString = require('../lang/toString'); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; },{"../lang/toString":27}],52:[function(require,module,exports){ var toString = require('../lang/toString'); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them if (str.search(/[\xC0-\xFF]/g) > -1) { str = str .replace(/[\xC0-\xC5]/g, "A") .replace(/[\xC6]/g, "AE") .replace(/[\xC7]/g, "C") .replace(/[\xC8-\xCB]/g, "E") .replace(/[\xCC-\xCF]/g, "I") .replace(/[\xD0]/g, "D") .replace(/[\xD1]/g, "N") .replace(/[\xD2-\xD6\xD8]/g, "O") .replace(/[\xD9-\xDC]/g, "U") .replace(/[\xDD]/g, "Y") .replace(/[\xDE]/g, "P") .replace(/[\xE0-\xE5]/g, "a") .replace(/[\xE6]/g, "ae") .replace(/[\xE7]/g, "c") .replace(/[\xE8-\xEB]/g, "e") .replace(/[\xEC-\xEF]/g, "i") .replace(/[\xF1]/g, "n") .replace(/[\xF2-\xF6\xF8]/g, "o") .replace(/[\xF9-\xFC]/g, "u") .replace(/[\xFE]/g, "p") .replace(/[\xFD\xFF]/g, "y"); } return str; } module.exports = replaceAccents; },{"../lang/toString":27}],53:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; },{"../lang/toString":27}],54:[function(require,module,exports){ /** * @doc function * @id DSHttpAdapterProvider * @name DSHttpAdapterProvider */ function DSHttpAdapterProvider() { /** * @doc property * @id DSHttpAdapterProvider.properties:defaults * @name defaults * @description * Default configuration for this adapter. * * Properties: * * - `{function}` - `queryTransform` - See [the guide](/documentation/guide/adapters/index). Default: No-op. */ var defaults = this.defaults = { /** * @doc property * @id DSHttpAdapterProvider.properties:defaults.queryTransform * @name defaults.queryTransform * @description * Transform the angular-data query to something your server understands. You might just do this on the server instead. * * ## Example: * ```js * DSHttpAdapterProvider.defaults.queryTransform = function (resourceName, params) { * if (params && params.userId) { * params.user_id = params.userId; * delete params.userId; * } * return params; * }; * ``` * * @param {string} resourceName The name of the resource. * @param {object} params Params that will be passed to `$http`. * @returns {*} By default just returns `params` as-is. */ queryTransform: function (resourceName, params) { return params; }, forceTrailingSlash: false, /** * @doc property * @id DSHttpAdapterProvider.properties:defaults.$httpConfig * @name defaults.$httpConfig * @description * Default `$http` configuration options used whenever `DSHttpAdapter` uses `$http`. * * ## Example: * ```js * angular.module('myApp').config(function (DSHttpAdapterProvider) { * angular.extend(DSHttpAdapterProvider.defaults.$httpConfig, { * headers: { * Authorization: 'Basic YmVlcDpib29w' * }, * timeout: 20000 * }); * }); * ``` */ $httpConfig: {} }; this.$get = ['$http', '$log', 'DSUtils', function ($http, $log, DSUtils) { /** * @doc method * @id DSHttpAdapter.methods:getPath * @name getPath * @description * Return the path that would be used by this adapter for a given operation. * * ## Signature: * ```js * DSHttpAdapter.getPath(method, resourceConfig, id|attrs|params, options)) * ``` * * @param {string} method The name of the method . * @param {object} resourceConfig The object returned by DS.defineResource. * @param {string|object} id|attrs|params The id, attrs, or params that you would pass into the method. * @param {object} options Configuration options. * @returns {string} The path. */ function getPath(method, resourceConfig, id, options) { options = options || {}; var args = [ options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint((DSUtils.isString(id) || DSUtils.isNumber(id) || method === 'create') ? id : null, options) ]; if (method === 'find' || method === 'update' || method === 'destroy') { args.push(id); } return DSUtils.makePath.apply(DSUtils, args); } /** * @doc interface * @id DSHttpAdapter * @name DSHttpAdapter * @description * Default adapter used by angular-data. This adapter uses AJAX and JSON to send/retrieve data to/from a server. * Developers may provide custom adapters that implement the adapter interface. */ return { /** * @doc property * @id DSHttpAdapter.properties:defaults * @name defaults * @description * Reference to [DSHttpAdapterProvider.defaults](/documentation/api/api/DSHttpAdapterProvider.properties:defaults). */ defaults: defaults, getPath: getPath, /** * @doc method * @id DSHttpAdapter.methods:HTTP * @name HTTP * @description * A wrapper for `$http()`. * * ## Signature: * ```js * DSHttpAdapter.HTTP(config) * ``` * * @param {object} config Configuration object. * @returns {Promise} Promise. */ HTTP: function (config) { var start = new Date().getTime(); if (this.defaults.forceTrailingSlash && config.url[config.url.length] !== '/') { config.url += '/'; } config = DSUtils.deepMixIn(config, defaults.$httpConfig); return $http(config).then(function (data) { $log.debug(data.config.method + ' request:' + data.config.url + ' Time taken: ' + (new Date().getTime() - start) + 'ms', arguments); return data; }); }, /** * @doc method * @id DSHttpAdapter.methods:GET * @name GET * @description * A wrapper for `$http.get()`. * * ## Signature: * ```js * DSHttpAdapter.GET(url[, config]) * ``` * * @param {string} url The url of the request. * @param {object=} config Optional configuration. * @returns {Promise} Promise. */ GET: function (url, config) { config = config || {}; if (!('method' in config)) { config.method = 'GET'; } return this.HTTP(DSUtils.deepMixIn(config, { url: url })); }, /** * @doc method * @id DSHttpAdapter.methods:POST * @name POST * @description * A wrapper for `$http.post()`. * * ## Signature: * ```js * DSHttpAdapter.POST(url[, attrs][, config]) * ``` * * @param {string} url The url of the request. * @param {object=} attrs Request payload. * @param {object=} config Optional configuration. * @returns {Promise} Promise. */ POST: function (url, attrs, config) { config = config || {}; if (!('method' in config)) { config.method = 'POST'; } return this.HTTP(DSUtils.deepMixIn(config, { url: url, data: attrs })); }, /** * @doc method * @id DSHttpAdapter.methods:PUT * @name PUT * @description * A wrapper for `$http.put()`. * * ## Signature: * ```js * DSHttpAdapter.PUT(url[, attrs][, config]) * ``` * * @param {string} url The url of the request. * @param {object=} attrs Request payload. * @param {object=} config Optional configuration. * @returns {Promise} Promise. */ PUT: function (url, attrs, config) { config = config || {}; if (!('method' in config)) { config.method = 'PUT'; } return this.HTTP(DSUtils.deepMixIn(config, { url: url, data: attrs || {} })); }, /** * @doc method * @id DSHttpAdapter.methods:DEL * @name DEL * @description * A wrapper for `$http.delete()`. * * ## Signature: * ```js * DSHttpAdapter.DEL(url[, config]) * ``` * * @param {string} url The url of the request. * @param {object=} config Optional configuration. * @returns {Promise} Promise. */ DEL: function (url, config) { config = config || {}; if (!('method' in config)) { config.method = 'DELETE'; } return this.HTTP(DSUtils.deepMixIn(config, { url: url })); }, /** * @doc method * @id DSHttpAdapter.methods:find * @name find * @description * Retrieve a single entity from the server. * * Makes a `GET` request. * * ## Signature: * ```js * DSHttpAdapter.find(resourceConfig, id[, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to update. * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Override the default base url. * - `{string=}` - `endpoint` - Override the default endpoint. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ find: function (resourceConfig, id, options) { options = options || {}; return this.GET( getPath('find', resourceConfig, id, options), options ); }, /** * @doc method * @id DSHttpAdapter.methods:findAll * @name findAll * @description * Retrieve a collection of entities from the server. * * Makes a `GET` request. * * ## Signature: * ```js * DSHttpAdapter.findAll(resourceConfig[, params][, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object=} params Search query parameters. See the [query guide](/documentation/guide/queries/index). * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Override the default base url. * - `{string=}` - `endpoint` - Override the default endpoint. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ findAll: function (resourceConfig, params, options) { options = options || {}; options.params = options.params || {}; if (params) { params = defaults.queryTransform(resourceConfig.name, params); DSUtils.deepMixIn(options.params, params); } return this.GET( getPath('findAll', resourceConfig, params, options), options ); }, /** * @doc method * @id DSHttpAdapter.methods:create * @name create * @description * Create a new entity on the server. * * Makes a `POST` request. * * ## Signature: * ```js * DSHttpAdapter.create(resourceConfig, attrs[, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object} attrs The attribute payload. * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Override the default base url. * - `{string=}` - `endpoint` - Override the default endpoint. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ create: function (resourceConfig, attrs, options) { options = options || {}; return this.POST( getPath('create', resourceConfig, attrs, options), attrs, options ); }, /** * @doc method * @id DSHttpAdapter.methods:update * @name update * @description * Update an entity on the server. * * Makes a `PUT` request. * * ## Signature: * ```js * DSHttpAdapter.update(resourceConfig, id, attrs[, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to update. * @param {object} attrs The attribute payload. * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Override the default base url. * - `{string=}` - `endpoint` - Override the default endpoint. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ update: function (resourceConfig, id, attrs, options) { options = options || {}; return this.PUT( getPath('update', resourceConfig, id, options), attrs, options ); }, /** * @doc method * @id DSHttpAdapter.methods:updateAll * @name updateAll * @description * Update a collection of entities on the server. * * Makes a `PUT` request. * * ## Signature: * ```js * DSHttpAdapter.updateAll(resourceConfig, attrs[, params][, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object} attrs The attribute payload. * @param {object=} params Search query parameters. See the [query guide](/documentation/guide/queries/index). * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Override the default base url. * - `{string=}` - `endpoint` - Override the default endpoint. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ updateAll: function (resourceConfig, attrs, params, options) { options = options || {}; options.params = options.params || {}; if (params) { params = defaults.queryTransform(resourceConfig.name, params); DSUtils.deepMixIn(options.params, params); } return this.PUT( getPath('updateAll', resourceConfig, attrs, options), attrs, options ); }, /** * @doc method * @id DSHttpAdapter.methods:destroy * @name destroy * @description * Delete an entity on the server. * * Makes a `DELETE` request. * * ## Signature: * ```js * DSHttpAdapter.destroy(resourceConfig, id[, options) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to update. * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Override the default base url. * - `{string=}` - `endpoint` - Override the default endpoint. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ destroy: function (resourceConfig, id, options) { options = options || {}; return this.DEL( getPath('destroy', resourceConfig, id, options), options ); }, /** * @doc method * @id DSHttpAdapter.methods:destroyAll * @name destroyAll * @description * Delete a collection of entities on the server. * * Makes `DELETE` request. * * ## Signature: * ```js * DSHttpAdapter.destroyAll(resourceConfig[, params][, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object=} params Search query parameters. See the [query guide](/documentation/guide/queries/index). * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Override the default base url. * - `{string=}` - `endpoint` - Override the default endpoint. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ destroyAll: function (resourceConfig, params, options) { options = options || {}; options.params = options.params || {}; if (params) { params = defaults.queryTransform(resourceConfig.name, params); DSUtils.deepMixIn(options.params, params); } return this.DEL( getPath('destroyAll', resourceConfig, params, options), options ); } }; }]; } module.exports = DSHttpAdapterProvider; },{}],55:[function(require,module,exports){ /*! * @doc function * @id DSLocalStorageAdapterProvider * @name DSLocalStorageAdapterProvider */ function DSLocalStorageAdapterProvider() { this.$get = ['$q', 'DSUtils', 'DSErrors', function ($q, DSUtils) { /** * @doc method * @id DSLocalStorageAdapter.methods:getPath * @name getPath * @description * Return the path that would be used by this adapter for a given operation. * * ## Signature: * ```js * DSLocalStorageAdapter.getPath(method, resourceConfig, id|attrs|params, options)) * ``` * * @param {string} method The name of the method . * @param {object} resourceConfig The object returned by DS.defineResource. * @param {string|object} id|attrs|params The id, attrs, or params that you would pass into the method. * @param {object} options Configuration options. * @returns {string} The path. */ function getPath(method, resourceConfig, id, options) { options = options || {}; var args = [ options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint((DSUtils.isString(id) || DSUtils.isNumber(id) || method === 'create') ? id : null, options) ]; if (method === 'find' || method === 'update' || method === 'destroy') { args.push(id); } return DSUtils.makePath.apply(DSUtils, args); } /** * @doc interface * @id DSLocalStorageAdapter * @name DSLocalStorageAdapter * @description * Adapter that uses `localStorage` as its persistence layer. The localStorage adapter does not support operations * on collections because localStorage itself is a key-value store. */ return { getIds: function (name, options) { var ids; var idsPath = DSUtils.makePath(options.baseUrl, 'DSKeys', name); var idsJson = localStorage.getItem(idsPath); if (idsJson) { ids = DSUtils.fromJson(idsJson); } else { localStorage.setItem(idsPath, DSUtils.toJson({})); ids = {}; } return ids; }, saveKeys: function (ids, name, options) { var keysPath = DSUtils.makePath(options.baseUrl, 'DSKeys', name); localStorage.setItem(keysPath, DSUtils.toJson(ids)); }, ensureId: function (id, name, options) { var ids = this.getIds(name, options); ids[id] = 1; this.saveKeys(ids, name, options); }, removeId: function (id, name, options) { var ids = this.getIds(name, options); delete ids[id]; this.saveKeys(ids, name, options); }, /** * @doc method * @id DSLocalStorageAdapter.methods:GET * @name GET * @description * An asynchronous wrapper for `localStorage.getItem(key)`. * * ## Signature: * ```js * DSLocalStorageAdapter.GET(key) * ``` * * @param {string} key The key path of the item to retrieve. * @returns {Promise} Promise. */ GET: function (key) { var deferred = $q.defer(); try { var item = localStorage.getItem(key); deferred.resolve(item ? angular.fromJson(item) : undefined); } catch (err) { deferred.reject(err); } return deferred.promise; }, /** * @doc method * @id DSLocalStorageAdapter.methods:PUT * @name PUT * @description * An asynchronous wrapper for `localStorage.setItem(key, value)`. * * ## Signature: * ```js * DSLocalStorageAdapter.PUT(key, value) * ``` * * @param {string} key The key to update. * @param {object} value Attributes to put. * @returns {Promise} Promise. */ PUT: function (key, value) { var DSLocalStorageAdapter = this; return DSLocalStorageAdapter.GET(key).then(function (item) { if (item) { DSUtils.deepMixIn(item, value); } localStorage.setItem(key, JSON.stringify(item || value)); return DSLocalStorageAdapter.GET(key); }); }, /** * @doc method * @id DSLocalStorageAdapter.methods:DEL * @name DEL * @description * An asynchronous wrapper for `localStorage.removeItem(key)`. * * ## Signature: * ```js * DSLocalStorageAdapter.DEL(key) * ``` * * @param {string} key The key to remove. * @returns {Promise} Promise. */ DEL: function (key) { var deferred = $q.defer(); try { localStorage.removeItem(key); deferred.resolve(); } catch (err) { deferred.reject(err); } return deferred.promise; }, /** * @doc method * @id DSLocalStorageAdapter.methods:find * @name find * @description * Retrieve a single entity from localStorage. * * ## Signature: * ```js * DSLocalStorageAdapter.find(resourceConfig, id[, options]) * ``` * * ## Example: * ```js * DS.find('user', 5, { * adapter: 'DSLocalStorageAdapter' * }).then(function (user) { * user; // { id: 5, ... } * }); * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to retrieve. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ find: function find(resourceConfig, id, options) { options = options || {}; return this.GET(getPath('find', resourceConfig, id, options)).then(function (item) { if (!item) { return $q.reject(new Error('Not Found!')); } else { return item; } }); }, /** * @doc method * @id DSLocalStorageAdapter.methods:findAll * @name findAll * @description * Retrieve a collections of entities from localStorage. * * ## Signature: * ```js * DSLocalStorageAdapter.findAll(resourceConfig, params[, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object=} params Query parameters. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ findAll: function (resourceConfig, params, options) { var _this = this; var deferred = $q.defer(); options = options || {}; if (!('allowSimpleWhere' in options)) { options.allowSimpleWhere = true; } var items = []; var ids = DSUtils.keys(_this.getIds(resourceConfig.name, options)); DSUtils.forEach(ids, function (id) { var itemJson = localStorage.getItem(getPath('find', resourceConfig, id, options)); if (itemJson) { items.push(DSUtils.fromJson(itemJson)); } }); deferred.resolve(_this.DS.defaults.defaultFilter.call(_this.DS, items, resourceConfig.name, params, options)); return deferred.promise; }, /** * @doc method * @id DSLocalStorageAdapter.methods:create * @name create * @description * Create an entity in `localStorage`. You must generate the primary key and include it in the `attrs` object. * * ## Signature: * ```js * DSLocalStorageAdapter.create(resourceConfig, attrs[, options]) * ``` * * ## Example: * ```js * DS.create('user', { * id: 1, * name: 'john' * }, { * adapter: 'DSLocalStorageAdapter' * }).then(function (user) { * user; // { id: 1, name: 'john' } * }); * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object} attrs Attributes to create in localStorage. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ create: function (resourceConfig, attrs, options) { var _this = this; var id = attrs[resourceConfig.idAttribute]; options = options || {}; return _this.GET(getPath('find', resourceConfig, id, options)).then(function (item) { if (item) { DSUtils.deepMixIn(item, attrs); } else { attrs[resourceConfig.idAttribute] = id = id || DSUtils.guid(); } return _this.PUT(getPath('update', resourceConfig, id, options), item || attrs); }).then(function (item) { _this.ensureId(item[resourceConfig.idAttribute], resourceConfig.name, options); return item; }); }, /** * @doc method * @id DSLocalStorageAdapter.methods:update * @name update * @description * Update an entity in localStorage. * * ## Signature: * ```js * DSLocalStorageAdapter.update(resourceConfig, id, attrs[, options]) * ``` * * ## Example: * ```js * DS.update('user', 5, { * name: 'john' * }, { * adapter: 'DSLocalStorageAdapter' * }).then(function (user) { * user; // { id: 5, ... } * }); * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to retrieve. * @param {object} attrs Attributes with which to update the entity. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ update: function (resourceConfig, id, attrs, options) { options = options || {}; var _this = this; return _this.GET(getPath('find', resourceConfig, id, options)).then(function (item) { item = item || {}; DSUtils.deepMixIn(item, attrs); return _this.PUT(getPath('update', resourceConfig, id, options), item); }).then(function (item) { _this.ensureId(item[resourceConfig.idAttribute], resourceConfig.name, options); return item; }); }, /** * @doc method * @id DSLocalStorageAdapter.methods:updateAll * @name updateAll * @description * Update a collections of entities in localStorage. * * ## Signature: * ```js * DSLocalStorageAdapter.updateAll(resourceConfig, attrs, params[, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object} attrs Attributes with which to update the items. * @param {object=} params Query parameters. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ updateAll: function (resourceConfig, attrs, params, options) { var _this = this; return this.findAll(resourceConfig, params, options).then(function (items) { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(_this.update(resourceConfig, item[resourceConfig.idAttribute], attrs, options)); }); return $q.all(tasks); }); }, /** * @doc method * @id DSLocalStorageAdapter.methods:destroy * @name destroy * @description * Destroy an entity from localStorage. * * ## Signature: * ```js * DSLocalStorageAdapter.destroy(resourceConfig, id[, options]) * ``` * * ## Example: * ```js * DS.destroy('user', 5, { * name: '' * }, { * adapter: 'DSLocalStorageAdapter' * }).then(function (user) { * user; // { id: 5, ... } * }); * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to destroy. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ destroy: function (resourceConfig, id, options) { options = options || {}; return this.DEL(getPath('destroy', resourceConfig, id, options)); }, /** * @doc method * @id DSLocalStorageAdapter.methods:destroyAll * @name destroyAll * @description * Destroy a collections of entities from localStorage. * * ## Signature: * ```js * DSLocalStorageAdapter.destroyAll(resourceConfig, params[, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object=} params Query parameters. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ destroyAll: function (resourceConfig, params, options) { var _this = this; return this.findAll(resourceConfig, params, options).then(function (items) { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(_this.destroy(resourceConfig, item[resourceConfig.idAttribute], options)); }); return $q.all(tasks); }); } }; }]; } module.exports = DSLocalStorageAdapterProvider; },{}],56:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.create(' + resourceName + ', attrs[, options]): '; } /** * @doc method * @id DS.async methods:create * @name create * @description * The "C" in "CRUD". Delegate to the `create` method of whichever adapter is being used (http by default) and inject the * result into the data store. * * ## Signature: * ```js * DS.create(resourceName, attrs[, options]) * ``` * * ## Example: * * ```js * DS.create('document', { * author: 'John Anderson' * }).then(function (document) { * document; // { id: 5, author: 'John Anderson' } * * // The new document is already in the data store * DS.get('document', document.id); // { id: 5, author: 'John Anderson' } * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} attrs The attributes with which to create the item of the type specified by `resourceName`. * @param {object=} options Configuration options. Also passed along to the adapter's `create` method. Properties: * * - `{boolean=}` - `useClass` - Whether to wrap the injected item with the resource's instance constructor. * - `{boolean=}` - `cacheResponse` - Inject the data returned by the adapter into the data store. Default: `true`. * - `{boolean=}` - `upsert` - If `attrs` already contains a primary key, then attempt to call `DS.update` instead. Default: `true`. * - `{boolean=}` - `eagerInject` - Eagerly inject the attributes into the store without waiting for a successful response from the adapter. Default: `false`. * - `{function=}` - `beforeValidate` - Override the resource or global lifecycle hook. * - `{function=}` - `validate` - Override the resource or global lifecycle hook. * - `{function=}` - `afterValidate` - Override the resource or global lifecycle hook. * - `{function=}` - `beforeCreate` - Override the resource or global lifecycle hook. * - `{function=}` - `afterCreate` - Override the resource or global lifecycle hook. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - A reference to the newly created item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function create(resourceName, attrs, options) { var DS = this; var DSUtils = DS.utils; var deferred = DS.$q.defer(); try { var definition = DS.definitions[resourceName]; var injected; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DSUtils.isObject(attrs)) { throw new DS.errors.IA(errorPrefix(resourceName) + 'attrs: Must be an object!'); } options = DSUtils._(definition, options); deferred.resolve(attrs); if (options.upsert && attrs[definition.idAttribute]) { return DS.update(resourceName, attrs[definition.idAttribute], attrs, options); } else { return deferred.promise .then(function (attrs) { return options.beforeValidate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.validate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.beforeCreate.call(attrs, resourceName, attrs); }) .then(function (attrs) { if (options.notify) { DS.emit(definition, 'beforeCreate', DSUtils.merge({}, attrs)); } if (options.eagerInject && options.cacheResponse) { attrs[definition.idAttribute] = attrs[definition.idAttribute] || DSUtils.guid(); injected = DS.inject(resourceName, attrs); } return DS.adapters[options.adapter || definition.defaultAdapter].create(definition, options.serialize ? options.serialize(resourceName, attrs) : definition.serialize(resourceName, attrs), options); }) .then(function (res) { var attrs = options.deserialize ? options.deserialize(resourceName, res) : definition.deserialize(resourceName, res); return options.afterCreate.call(attrs, resourceName, attrs); }) .then(function (attrs) { if (options.notify) { DS.emit(definition, 'afterCreate', DSUtils.merge({}, attrs)); } if (options.cacheResponse) { var resource = DS.store[resourceName]; if (options.eagerInject) { var newId = attrs[definition.idAttribute]; var prevId = injected[definition.idAttribute]; var prev = DS.get(resourceName, prevId); resource.previousAttributes[newId] = resource.previousAttributes[prevId]; resource.changeHistories[newId] = resource.changeHistories[prevId]; resource.observers[newId] = resource.observers[prevId]; resource.modified[newId] = resource.modified[prevId]; resource.saved[newId] = resource.saved[prevId]; resource.index.put(newId, prev); DS.eject(resourceName, prevId, { notify: false }); prev[definition.idAttribute] = newId; resource.collection.push(prev); } var created = DS.inject(resourceName, attrs, options); var id = created[definition.idAttribute]; resource.completedQueries[id] = new Date().getTime(); resource.previousAttributes[id] = DSUtils.deepMixIn({}, created); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return DS.get(resourceName, id); } else { return DS.createInstance(resourceName, attrs, options); } })['catch'](function (err) { if (options.eagerInject && options.cacheResponse) { DS.eject(resourceName, injected[definition.idAttribute], { notify: false }); } return DS.$q.reject(err); }); } } catch (err) { deferred.reject(err); return deferred.promise; } } module.exports = create; },{}],57:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.destroy(' + resourceName + ', ' + id + '[, options]): '; } /** * @doc method * @id DS.async methods:destroy * @name destroy * @description * The "D" in "CRUD". Delegate to the `destroy` method of whichever adapter is being used (http by default) and eject the * appropriate item from the data store. * * ## Signature: * ```js * DS.destroy(resourceName, id[, options]); * ``` * * ## Example: * * ```js * DS.destroy('document', 5).then(function (id) { * id; // 5 * * // The document is gone * DS.get('document', 5); // undefined * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to remove. * @param {object=} options Configuration options. Also passed along to the adapter's `destroy` method. Properties: * * - `{function=}` - `beforeDestroy` - Override the resource or global lifecycle hook. * - `{function=}` - `afterDestroy` - Override the resource or global lifecycle hook. * - `{boolean=}` - `eagerEject` - If `true` eagerly eject the item from the store without waiting for the adapter's response, the item will be re-injected if the adapter operation fails. Default: `false`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{string|number}` - `id` - The primary key of the destroyed item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{NonexistentResourceError}` */ function destroy(resourceName, id, options) { var DS = this; var DSUtils = DS.utils; var deferred = DS.$q.defer(); try { var definition = DS.definitions[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } var item = DS.get(resourceName, id); if (!item) { throw new DS.errors.R(errorPrefix(resourceName, id) + 'id: "' + id + '" not found!'); } options = DSUtils._(definition, options); deferred.resolve(item); return deferred.promise .then(function (attrs) { return options.beforeDestroy.call(attrs, resourceName, attrs); }) .then(function (attrs) { if (options.notify) { DS.emit(definition, 'beforeDestroy', DSUtils.merge({}, attrs)); } if (options.eagerEject) { DS.eject(resourceName, id); } return DS.adapters[options.adapter || definition.defaultAdapter].destroy(definition, id, options); }) .then(function () { return options.afterDestroy.call(item, resourceName, item); }) .then(function () { if (options.notify) { DS.emit(definition, 'afterDestroy', DSUtils.merge({}, item)); } DS.eject(resourceName, id); return id; })['catch'](function (err) { if (options.eagerEject && item) { DS.inject(resourceName, item); } return DS.$q.reject(err); }); } catch (err) { deferred.reject(err); return deferred.promise; } } module.exports = destroy; },{}],58:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.destroyAll(' + resourceName + ', params[, options]): '; } /** * @doc method * @id DS.async methods:destroyAll * @name destroyAll * @description * The "D" in "CRUD". Delegate to the `destroyAll` method of whichever adapter is being used (http by default) and eject * the appropriate items from the data store. * * ## Signature: * ```js * DS.destroyAll(resourceName, params[, options]) * ``` * * ## Example: * * ```js * var params = { * where: { * author: { * '==': 'John Anderson' * } * } * }; * * DS.destroyAll('document', params).then(function (documents) { * // The documents are gone from the data store * DS.filter('document', params); // [] * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} params Parameter object that is serialized into the query string. Properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Also passed along to the adapter's `destroyAll` method. Properties: * * - `{boolean=}` - `bypassCache` - Bypass the cache. Default: `false`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function destroyAll(resourceName, params, options) { var DS = this; var DSUtils = DS.utils; var deferred = DS.$q.defer(); try { var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DSUtils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } else if (!DSUtils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } options = DSUtils._(definition, options); deferred.resolve(); return deferred.promise .then(function () { return DS.adapters[options.adapter || definition.defaultAdapter].destroyAll(definition, params, options); }) .then(function () { return DS.ejectAll(resourceName, params); }); } catch (err) { deferred.reject(err); return deferred.promise; } } module.exports = destroyAll; },{}],59:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.find(' + resourceName + ', ' + id + '[, options]): '; } /** * @doc method * @id DS.async methods:find * @name find * @description * The "R" in "CRUD". Delegate to the `find` method of whichever adapter is being used (http by default) and inject the * resulting item into the data store. * * ## Signature: * ```js * DS.find(resourceName, id[, options]) * ``` * * ## Example: * * ```js * DS.get('document', 5); // undefined * DS.find('document', 5).then(function (document) { * document; // { id: 5, author: 'John Anderson' } * * // the document is now in the data store * DS.get('document', 5); // { id: 5, author: 'John Anderson' } * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to retrieve. * @param {object=} options Optional configuration. Also passed along to the adapter's `find` method. Properties: * * - `{boolean=}` - `useClass` - Whether to wrap the injected item with the resource's instance constructor. * - `{boolean=}` - `bypassCache` - Bypass the cache. Default: `false`. * - `{boolean=}` - `cacheResponse` - Inject the data returned by the adapter into the data store. Default: `true`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - The item returned by the adapter. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function find(resourceName, id, options) { var DS = this; var DSUtils = DS.utils; var deferred = DS.$q.defer(); var promise = deferred.promise; try { var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } else if (!DSUtils.isObject(options)) { throw new IA(errorPrefix(resourceName, id) + 'options: Must be an object!'); } options = DSUtils._(definition, options); var resource = DS.store[resourceName]; if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if (!(id in resource.completedQueries)) { if (!(id in resource.pendingQueries)) { promise = resource.pendingQueries[id] = DS.adapters[options.adapter || definition.defaultAdapter].find(definition, id, options) .then(function (res) { var data = options.deserialize ? options.deserialize(resourceName, res) : definition.deserialize(resourceName, res); // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { resource.completedQueries[id] = new Date().getTime(); return DS.inject(resourceName, data, options); } else { return DS.createInstance(resourceName, data, options); } }, function (err) { delete resource.pendingQueries[id]; return DS.$q.reject(err); }); } return resource.pendingQueries[id]; } else { deferred.resolve(DS.get(resourceName, id)); } } catch (err) { deferred.reject(err); } return promise; } module.exports = find; },{}],60:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.findAll(' + resourceName + ', params[, options]): '; } function processResults(data, resourceName, queryHash, options) { var DS = this; var DSUtils = DS.utils; var resource = DS.store[resourceName]; var idAttribute = DS.definitions[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Update modified timestamp of collection resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); // Merge the new values into the cache var injected = DS.inject(resourceName, data, options); // Make sure each object is added to completedQueries if (DSUtils.isArray(injected)) { angular.forEach(injected, function (item) { if (item && item[idAttribute]) { resource.completedQueries[item[idAttribute]] = date; } }); } else { DS.$log.warn(errorPrefix(resourceName) + 'response is expected to be an array!'); resource.completedQueries[injected[idAttribute]] = date; } return injected; } function _findAll(resourceName, params, options) { var DS = this; var DSUtils = DS.utils; var definition = DS.definitions[resourceName]; var resource = DS.store[resourceName]; var queryHash = DSUtils.toJson(params); if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; } if (!(queryHash in resource.completedQueries)) { // This particular query has never been completed if (!(queryHash in resource.pendingQueries)) { // This particular query has never even been made resource.pendingQueries[queryHash] = DS.adapters[options.adapter || definition.defaultAdapter].findAll(definition, params, options) .then(function (res) { delete resource.pendingQueries[queryHash]; var data = options.deserialize ? options.deserialize(resourceName, res) : definition.deserialize(resourceName, res); if (options.cacheResponse) { try { return processResults.call(DS, data, resourceName, queryHash, options); } catch (err) { return DS.$q.reject(err); } } else { DSUtils.forEach(data, function (item, i) { data[i] = DS.createInstance(resourceName, item, options); }); return data; } }, function (err) { delete resource.pendingQueries[queryHash]; return DS.$q.reject(err); }); } return resource.pendingQueries[queryHash]; } else { return DS.filter(resourceName, params, options); } } /** * @doc method * @id DS.async methods:findAll * @name findAll * @description * The "R" in "CRUD". Delegate to the `findAll` method of whichever adapter is being used (http by default) and inject * the resulting collection into the data store. * * ## Signature: * ```js * DS.findAll(resourceName, params[, options]) * ``` * * ## Example: * * ```js * var params = { * where: { * author: { * '==': 'John Anderson' * } * } * }; * * DS.filter('document', params); // [] * DS.findAll('document', params).then(function (documents) { * documents; // [{ id: '1', author: 'John Anderson', title: 'How to cook' }, * // { id: '2', author: 'John Anderson', title: 'How NOT to cook' }] * * // The documents are now in the data store * DS.filter('document', params); // [{ id: '1', author: 'John Anderson', title: 'How to cook' }, * // { id: '2', author: 'John Anderson', title: 'How NOT to cook' }] * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object=} params Parameter object that is serialized into the query string. Default properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Also passed along to the adapter's `findAll` method. Properties: * * - `{boolean=}` - `useClass` - Whether to wrap the injected item with the resource's instance constructor. * - `{boolean=}` - `bypassCache` - Bypass the cache. Default: `false`. * - `{boolean=}` - `cacheResponse` - Inject the data returned by the adapter into the data store. Default: `true`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{array}` - `items` - The collection of items returned by the adapter. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function findAll(resourceName, params, options) { var DS = this; var DSUtils = DS.utils; var deferred = DS.$q.defer(); var definition = DS.definitions[resourceName]; try { var IA = DS.errors.IA; options = options || {}; params = params || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DSUtils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } else if (!DSUtils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } options = DSUtils._(definition, options); deferred.resolve(); return deferred.promise.then(function () { return _findAll.call(DS, resourceName, params, options); }); } catch (err) { deferred.reject(err); return deferred.promise; } } module.exports = findAll; },{}],61:[function(require,module,exports){ module.exports = { /** * @doc method * @id DS.async methods:create * @name create * @methodOf DS * @description * See [DS.create](/documentation/api/api/DS.async methods:create). */ create: require('./create'), /** * @doc method * @id DS.async methods:destroy * @name destroy * @methodOf DS * @description * See [DS.destroy](/documentation/api/api/DS.async methods:destroy). */ destroy: require('./destroy'), /** * @doc method * @id DS.async methods:destroyAll * @name destroyAll * @methodOf DS * @description * See [DS.destroyAll](/documentation/api/api/DS.async methods:destroyAll). */ destroyAll: require('./destroyAll'), /** * @doc method * @id DS.async methods:find * @name find * @methodOf DS * @description * See [DS.find](/documentation/api/api/DS.async methods:find). */ find: require('./find'), /** * @doc method * @id DS.async methods:findAll * @name findAll * @methodOf DS * @description * See [DS.findAll](/documentation/api/api/DS.async methods:findAll). */ findAll: require('./findAll'), /** * @doc method * @id DS.async methods:loadRelations * @name loadRelations * @methodOf DS * @description * See [DS.loadRelations](/documentation/api/api/DS.async methods:loadRelations). */ loadRelations: require('./loadRelations'), /** * @doc method * @id DS.async methods:refresh * @name refresh * @methodOf DS * @description * See [DS.refresh](/documentation/api/api/DS.async methods:refresh). */ refresh: require('./refresh'), /** * @doc method * @id DS.async methods:save * @name save * @methodOf DS * @description * See [DS.save](/documentation/api/api/DS.async methods:save). */ save: require('./save'), /** * @doc method * @id DS.async methods:update * @name update * @methodOf DS * @description * See [DS.update](/documentation/api/api/DS.async methods:update). */ update: require('./update'), /** * @doc method * @id DS.async methods:updateAll * @name updateAll * @methodOf DS * @description * See [DS.updateAll](/documentation/api/api/DS.async methods:updateAll). */ updateAll: require('./updateAll') }; },{"./create":56,"./destroy":57,"./destroyAll":58,"./find":59,"./findAll":60,"./loadRelations":62,"./refresh":63,"./save":64,"./update":65,"./updateAll":66}],62:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.loadRelations(' + resourceName + ', instance(Id), relations[, options]): '; } /** * @doc method * @id DS.async methods:loadRelations * @name loadRelations * @description * Asynchronously load the indicated relations of the given instance. * * ## Signature: * ```js * DS.loadRelations(resourceName, instance|id, relations[, options]) * ``` * * ## Examples: * * ```js * DS.loadRelations('user', 10, ['profile']).then(function (user) { * user.profile; // object * assert.deepEqual(user.profile, DS.filter('profile', { userId: 10 })[0]); * }); * ``` * * ```js * var user = DS.get('user', 10); * * DS.loadRelations('user', user, ['profile']).then(function (user) { * user.profile; // object * assert.deepEqual(user.profile, DS.filter('profile', { userId: 10 })[0]); * }); * ``` * * ```js * DS.loadRelations('user', 10, ['profile'], { cacheResponse: false }).then(function (user) { * user.profile; // object * assert.equal(DS.filter('profile', { userId: 10 }).length, 0); * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number|object} instance The instance or the id of the instance for which relations are to be loaded. * @param {string|array=} relations The relation(s) to load. * @param {object=} options Optional configuration. Also passed along to the adapter's `find` or `findAll` methods. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - The instance with its loaded relations. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function loadRelations(resourceName, instance, relations, options) { var DS = this; var DSUtils = DS.utils; var deferred = DS.$q.defer(); try { var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; options = options || {}; if (DSUtils.isString(instance) || DSUtils.isNumber(instance)) { instance = DS.get(resourceName, instance); } if (angular.isString(relations)) { relations = [relations]; } if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DSUtils.isObject(instance)) { throw new IA(errorPrefix(resourceName) + 'instance(Id): Must be a string, number or object!'); } else if (!DSUtils.isArray(relations)) { throw new IA(errorPrefix(resourceName) + 'relations: Must be a string or an array!'); } else if (!DSUtils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } options = DSUtils._(definition, options); if (!options.hasOwnProperty('findBelongsTo')) { options.findBelongsTo = true; } if (!options.hasOwnProperty('findHasMany')) { options.findHasMany = true; } var tasks = []; var fields = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (DSUtils.contains(relations, relationName)) { var task; var params = {}; if (options.allowSimpleWhere) { params[def.foreignKey] = instance[definition.idAttribute]; } else { params.where = {}; params.where[def.foreignKey] = { '==': instance[definition.idAttribute] }; } if (def.type === 'hasMany' && params[def.foreignKey]) { task = DS.findAll(relationName, params, options); } else if (def.type === 'hasOne') { if (def.localKey && instance[def.localKey]) { task = DS.find(relationName, instance[def.localKey], options); } else if (def.foreignKey && params[def.foreignKey]) { task = DS.findAll(relationName, params, options).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = DS.find(relationName, instance[def.localKey], options); } if (task) { tasks.push(task); fields.push(def.localField); } } }); deferred.resolve(); return deferred.promise .then(function () { return DS.$q.all(tasks); }) .then(function (loadedRelations) { angular.forEach(fields, function (field, index) { instance[field] = loadedRelations[index]; }); return instance; }); } catch (err) { deferred.reject(err); return deferred.promise; } } module.exports = loadRelations; },{}],63:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.refresh(' + resourceName + ', ' + id + '[, options]): '; } /** * @doc method * @id DS.async methods:refresh * @name refresh * @description * Like `DS.find`, except the resource is only refreshed from the adapter if it already exists in the data store. * * ## Signature: * ```js * DS.refresh(resourceName, id[, options]) * ``` * ## Example: * * ```js * // Exists in the data store, but we want a fresh copy * DS.get('document', 5); * * DS.refresh('document', 5).then(function (document) { * document; // The fresh copy * }); * * // Does not exist in the data store * DS.get('document', 6); // undefined * * DS.refresh('document', 6).then(function (document) { * document; // undefined * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to refresh from the adapter. * @param {object=} options Optional configuration. Also passed along to the adapter's `find` method. * @returns {Promise} A Promise created by the $q service. * * ## Resolves with: * * - `{object|undefined}` - `item` - The item returned by the adapter or `undefined` if the item wasn't already in the * data store. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function refresh(resourceName, id, options) { var DS = this; var DSUtils = DS.utils; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; options = options || {}; id = DSUtils.resolveId(DS.definitions[resourceName], id); if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } else if (!DSUtils.isObject(options)) { throw new IA(errorPrefix(resourceName, id) + 'options: Must be an object!'); } else { options = DSUtils._(definition, options); options.bypassCache = true; if (DS.get(resourceName, id)) { return DS.find(resourceName, id, options); } else { var deferred = DS.$q.defer(); deferred.resolve(); return deferred.promise; } } } module.exports = refresh; },{}],64:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.save(' + resourceName + ', ' + id + '[, options]): '; } /** * @doc method * @id DS.async methods:save * @name save * @description * The "U" in "CRUD". Persist a single item already in the store and in it's current form to whichever adapter is being * used (http by default) and inject the resulting item into the data store. * * ## Signature: * ```js * DS.save(resourceName, id[, options]) * ``` * * ## Example: * * ```js * var document = DS.get('document', 5); * * document.title = 'How to cook in style'; * * DS.save('document', 5).then(function (document) { * document; // A reference to the document that's been persisted via an adapter * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to save. * @param {object=} options Optional configuration. Also passed along to the adapter's `update` method. Properties: * * - `{boolean=}` - `cacheResponse` - Inject the data returned by the adapter into the data store. Default: `true`. * - `{boolean=}` - `changesOnly` - Only send changed and added values to the adapter. Default: `false`. * - `{function=}` - `beforeValidate` - Override the resource or global lifecycle hook. * - `{function=}` - `validate` - Override the resource or global lifecycle hook. * - `{function=}` - `afterValidate` - Override the resource or global lifecycle hook. * - `{function=}` - `beforeUpdate` - Override the resource or global lifecycle hook. * - `{function=}` - `afterUpdate` - Override the resource or global lifecycle hook. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - The item returned by the adapter. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{NonexistentResourceError}` */ function save(resourceName, id, options) { var DS = this; var DSUtils = DS.utils; var deferred = DS.$q.defer(); try { var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } else if (!DSUtils.isObject(options)) { throw new IA(errorPrefix(resourceName, id) + 'options: Must be an object!'); } var item = DS.get(resourceName, id); if (!item) { throw new DS.errors.R(errorPrefix(resourceName, id) + 'id: "' + id + '" not found!'); } options = DSUtils._(definition, options); deferred.resolve(item); return deferred.promise .then(function (attrs) { return options.beforeValidate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.validate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, resourceName, attrs); }) .then(function (attrs) { if (options.notify) { DS.emit(definition, 'beforeUpdate', DSUtils.merge({}, attrs)); } if (options.changesOnly) { var resource = DS.store[resourceName]; resource.observers[id].deliver(); var toKeep = [], changes = DS.changes(resourceName, id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); if (DSUtils.isEmpty(changes)) { // no changes, return return attrs; } else { attrs = changes; } } return DS.adapters[options.adapter || definition.defaultAdapter].update(definition, id, options.serialize ? options.serialize(resourceName, attrs) : definition.serialize(resourceName, attrs), options); }) .then(function (res) { var attrs = options.deserialize ? options.deserialize(resourceName, res) : definition.deserialize(resourceName, res); return options.afterUpdate.call(attrs, resourceName, attrs); }) .then(function (attrs) { if (options.notify) { DS.emit(definition, 'afterUpdate', DSUtils.merge({}, attrs)); } if (options.cacheResponse) { var resource = DS.store[resourceName]; var saved = DS.inject(definition.name, attrs, options); resource.previousAttributes[id] = DSUtils.deepMixIn({}, saved); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); resource.observers[id].discardChanges(); return DS.get(resourceName, id); } else { return attrs; } }); } catch (err) { deferred.reject(err); return deferred.promise; } } module.exports = save; },{}],65:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.update(' + resourceName + ', ' + id + ', attrs[, options]): '; } /** * @doc method * @id DS.async methods:update * @name update * @description * The "U" in "CRUD". Update the item of type `resourceName` and primary key `id` with `attrs`. This is useful when you * want to update an item that isn't already in the data store, or you don't want to update the item that's in the data * store until the adapter operation succeeds. This differs from `DS.save` which simply saves items in their current * form that already exist in the data store. The resulting item (by default) will be injected into the data store. * * ## Signature: * ```js * DS.update(resourceName, id, attrs[, options]) * ``` * * ## Example: * * ```js * DS.get('document', 5); // undefined * * DS.update('document', 5, { * title: 'How to cook in style' * }).then(function (document) { * document; // A reference to the document that's been saved via an adapter * // and now resides in the data store * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to update. * @param {object} attrs The attributes with which to update the item. * @param {object=} options Optional configuration. Also passed along to the adapter's `update` method. Properties: * * - `{boolean=}` - `cacheResponse` - Inject the data returned by the adapter into the data store. Default: `true`. * - `{function=}` - `beforeValidate` - Override the resource or global lifecycle hook. * - `{function=}` - `validate` - Override the resource or global lifecycle hook. * - `{function=}` - `afterValidate` - Override the resource or global lifecycle hook. * - `{function=}` - `beforeUpdate` - Override the resource or global lifecycle hook. * - `{function=}` - `afterUpdate` - Override the resource or global lifecycle hook. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - The item returned by the adapter. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function update(resourceName, id, attrs, options) { var DS = this; var DSUtils = DS.utils; var deferred = DS.$q.defer(); try { var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } else if (!DSUtils.isObject(attrs)) { throw new IA(errorPrefix(resourceName, id) + 'attrs: Must be an object!'); } else if (!DSUtils.isObject(options)) { throw new IA(errorPrefix(resourceName, id) + 'options: Must be an object!'); } options = DSUtils._(definition, options); deferred.resolve(attrs); return deferred.promise .then(function (attrs) { return options.beforeValidate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.validate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, resourceName, attrs); }) .then(function (attrs) { if (options.notify) { DS.emit(definition, 'beforeUpdate', DSUtils.merge({}, attrs)); } return DS.adapters[options.adapter || definition.defaultAdapter].update(definition, id, options.serialize ? options.serialize(resourceName, attrs) : definition.serialize(resourceName, attrs), options); }) .then(function (res) { var attrs = options.deserialize ? options.deserialize(resourceName, res) : definition.deserialize(resourceName, res); return options.afterUpdate.call(attrs, resourceName, attrs); }) .then(function (attrs) { if (options.notify) { DS.emit(definition, 'afterUpdate', DSUtils.merge({}, attrs)); } if (options.cacheResponse) { var resource = DS.store[resourceName]; var updated = DS.inject(definition.name, attrs, options); var id = updated[definition.idAttribute]; resource.previousAttributes[id] = DSUtils.deepMixIn({}, updated); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); resource.observers[id].discardChanges(); return DS.get(definition.name, id); } else { return attrs; } }); } catch (err) { deferred.reject(err); return deferred.promise; } } module.exports = update; },{}],66:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.updateAll(' + resourceName + ', attrs, params[, options]): '; } /** * @doc method * @id DS.async methods:updateAll * @name updateAll * @description * The "U" in "CRUD". Update items of type `resourceName` with `attrs` according to the criteria specified by `params`. * This is useful when you want to update multiple items with the same attributes or you don't want to update the items * in the data store until the adapter operation succeeds. The resulting items (by default) will be injected into the * data store. * * ## Signature: * ```js * DS.updateAll(resourceName, attrs, params[, options]) * ``` * * ## Example: * * ```js * var params = { * where: { * author: { * '==': 'John Anderson' * } * } * }; * * DS.filter('document', params); // [] * * DS.updateAll('document', { * author: 'Sally' * }, params).then(function (documents) { * documents; // The documents that were updated via an adapter * // and now reside in the data store * * documents[0].author; // "Sally" * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} attrs The attributes with which to update the items. * @param {object} params Parameter object that is serialized into the query string. Default properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Also passed along to the adapter's `updateAll` method. Properties: * * - `{boolean=}` - `cacheResponse` - Inject the items returned by the adapter into the data store. Default: `true`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{array}` - `items` - The items returned by the adapter. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function updateAll(resourceName, attrs, params, options) { var DS = this; var DSUtils = DS.utils; var deferred = DS.$q.defer(); try { var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DSUtils.isObject(attrs)) { throw new IA(errorPrefix(resourceName) + 'attrs: Must be an object!'); } else if (!DSUtils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } else if (!DSUtils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } options = DSUtils._(definition, options); deferred.resolve(attrs); return deferred.promise .then(function (attrs) { return options.beforeValidate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.validate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, resourceName, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, resourceName, attrs); }) .then(function (attrs) { if (options.notify) { DS.emit(definition, 'beforeUpdate', DSUtils.merge({}, attrs)); } return DS.adapters[options.adapter || definition.defaultAdapter].updateAll(definition, options.serialize ? options.serialize(resourceName, attrs) : definition.serialize(resourceName, attrs), params, options); }) .then(function (res) { var attrs = options.deserialize ? options.deserialize(resourceName, res) : definition.deserialize(resourceName, res); return options.afterUpdate.call(attrs, resourceName, attrs); }) .then(function (attrs) { if (options.notify) { DS.emit(definition, 'afterUpdate', DSUtils.merge({}, attrs)); } if (options.cacheResponse) { return DS.inject(definition.name, attrs, options); } else { return attrs; } }); } catch (err) { deferred.reject(err); return deferred.promise; } } module.exports = updateAll; },{}],67:[function(require,module,exports){ var observe = require('../../lib/observe-js/observe-js'); function lifecycleNoop(resourceName, attrs, cb) { cb(null, attrs); } function compare(DSUtils, orderBy, index, a, b) { var def = orderBy[index]; var cA = a[def[0]], cB = b[def[0]]; if (DSUtils.isString(cA)) { cA = DSUtils.upperCase(cA); } if (DSUtils.isString(cB)) { cB = DSUtils.upperCase(cB); } if (def[1] === 'DESC') { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { return compare(DSUtils, orderBy, index + 1, a, b); } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { return compare(DSUtils, orderBy, index + 1, a, b); } else { return 0; } } } } function Defaults() { } Defaults.prototype.idAttribute = 'id'; Defaults.prototype.defaultAdapter = 'DSHttpAdapter'; Defaults.prototype.defaultFilter = function (collection, resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var filtered = collection; var where = null; var reserved = { skip: '', offset: '', where: '', limit: '', orderBy: '', sort: '' }; params = params || {}; if (DSUtils.isObject(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { DSUtils.forEach(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { '==': value }; } }); } if (DSUtils.isEmpty(where)) { where = null; } if (where) { filtered = DSUtils.filter(filtered, function (attrs) { var first = true; var keep = true; DSUtils.forEach(where, function (clause, field) { if (DSUtils.isString(clause)) { clause = { '===': clause }; } else if (DSUtils.isNumber(clause) || DSUtils.isBoolean(clause)) { clause = { '==': clause }; } if (DSUtils.isObject(clause)) { DSUtils.forEach(clause, function (term, op) { var expr; var isOr = op[0] === '|'; var val = attrs[field]; op = isOr ? op.substr(1) : op; if (op === '==') { expr = val == term; } else if (op === '===') { expr = val === term; } else if (op === '!=') { expr = val != term; } else if (op === '!==') { expr = val !== term; } else if (op === '>') { expr = val > term; } else if (op === '>=') { expr = val >= term; } else if (op === '<') { expr = val < term; } else if (op === '<=') { expr = val <= term; } else if (op === 'in') { if (DSUtils.isString(term)) { expr = term.indexOf(val) !== -1; } else { expr = DSUtils.contains(term, val); } } else if (op === 'notIn') { if (DSUtils.isString(term)) { expr = term.indexOf(val) === -1; } else { expr = !DSUtils.contains(term, val); } } else if (op === 'contains') { if (DSUtils.isString(term)) { expr = (val || '').indexOf(term) !== -1; } else { expr = DSUtils.contains(val, term); } } else if (op === 'notContains') { if (DSUtils.isString(term)) { expr = (val || '').indexOf(term) === -1; } else { expr = !DSUtils.contains(val, term); } } if (expr !== undefined) { keep = first ? expr : (isOr ? keep || expr : keep && expr); } first = false; }); } }); return keep; }); } var orderBy = null; if (DSUtils.isString(params.orderBy)) { orderBy = [ [params.orderBy, 'ASC'] ]; } else if (DSUtils.isArray(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && DSUtils.isString(params.sort)) { orderBy = [ [params.sort, 'ASC'] ]; } else if (!orderBy && DSUtils.isArray(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { var index = 0; angular.forEach(orderBy, function (def, i) { if (DSUtils.isString(def)) { orderBy[i] = [def, 'ASC']; } else if (!DSUtils.isArray(def)) { throw new _this.errors.IllegalArgumentError('DS.filter(resourceName[, params][, options]): ' + JSON.stringify(def) + ': Must be a string or an array!', { params: { 'orderBy[i]': { actual: typeof def, expected: 'string|array' } } }); } filtered = DSUtils.sort(filtered, function (a, b) { return compare(DSUtils, orderBy, index, a, b); }); }); } var limit = angular.isNumber(params.limit) ? params.limit : null; var skip = null; if (angular.isNumber(params.skip)) { skip = params.skip; } else if (angular.isNumber(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = _this.utils.slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (_this.utils.isNumber(limit)) { filtered = _this.utils.slice(filtered, 0, Math.min(filtered.length, limit)); } else if (_this.utils.isNumber(skip)) { if (skip < filtered.length) { filtered = _this.utils.slice(filtered, skip); } else { filtered = []; } } return filtered; }; Defaults.prototype.baseUrl = ''; Defaults.prototype.endpoint = ''; Defaults.prototype.useClass = true; Defaults.prototype.keepChangeHistory = false; Defaults.prototype.resetHistoryOnInject = true; Defaults.prototype.eagerInject = false; Defaults.prototype.eagerEject = false; Defaults.prototype.notify = true; Defaults.prototype.cacheResponse = true; Defaults.prototype.upsert = true; Defaults.prototype.allowSimpleWhere = true; /** * @doc property * @id DSProvider.properties:defaults.ignoredChanges * @name defaults.ignoredChanges * @description * Array of strings or regular expressions which can be ignored when diffing two objects for changes * * ## Example: * ```js * // ignore $ or _ prefixed changes * DSProvider.defaults.ignoredChanges = [/\$|\_/]; * ``` * * @value {array} ignoredChanges Array of changes to ignore. Defaults to ignoring $ prefixed changes: [/\$/] */ Defaults.prototype.ignoredChanges = [/\$/]; /** * @doc property * @id DSProvider.properties:defaults.beforeValidate * @name defaults.beforeValidate * @description * Called before the `validate` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * beforeValidate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.beforeValidate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.beforeValidate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.validate * @name defaults.validate * @description * Called before the `afterValidate` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * validate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.validate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.validate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.afterValidate * @name defaults.afterValidate * @description * Called before the `beforeCreate` or `beforeUpdate` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * afterValidate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.afterValidate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.afterValidate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.beforeCreate * @name defaults.beforeCreate * @description * Called before the `create` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * beforeCreate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.beforeCreate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.beforeCreate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.afterCreate * @name defaults.afterCreate * @description * Called after the `create` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * afterCreate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.afterCreate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.afterCreate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.beforeUpdate * @name defaults.beforeUpdate * @description * Called before the `update` or `save` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * beforeUpdate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.beforeUpdate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.beforeUpdate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.afterUpdate * @name defaults.afterUpdate * @description * Called after the `update` or `save` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * afterUpdate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.afterUpdate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.afterUpdate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.beforeDestroy * @name defaults.beforeDestroy * @description * Called before the `destroy` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * beforeDestroy(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.beforeDestroy = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.beforeDestroy = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.afterDestroy * @name defaults.afterDestroy * @description * Called after the `destroy` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * afterDestroy(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.afterDestroy = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.afterDestroy = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.beforeInject * @name defaults.beforeInject * @description * Called before the `inject` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * beforeInject(resourceName, attrs) * ``` * * Throwing an error inside this step will cancel the injection. * * ## Example: * ```js * DSProvider.defaults.beforeInject = function (resourceName, attrs) { * // do somthing/inspect/modify attrs * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.beforeInject = function (resourceName, attrs) { return attrs; }; /** * @doc property * @id DSProvider.properties:defaults.afterInject * @name defaults.afterInject * @description * Called after the `inject` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * afterInject(resourceName, attrs) * ``` * * Throwing an error inside this step will cancel the injection. * * ## Example: * ```js * DSProvider.defaults.afterInject = function (resourceName, attrs) { * // do somthing/inspect/modify attrs * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.afterInject = function (resourceName, attrs) { return attrs; }; /** * @doc property * @id DSProvider.properties:defaults.serialize * @name defaults.serialize * @description * Your server might expect a custom request object rather than the plain POJO payload. Use `serialize` to * create your custom request object. * * ## Example: * ```js * DSProvider.defaults.serialize = function (resourceName, data) { * return { * payload: data * }; * }; * ``` * * @param {string} resourceName The name of the resource to serialize. * @param {object} data Data to be sent to the server. * @returns {*} By default returns `data` as-is. */ Defaults.prototype.serialize = function (resourceName, data) { return data; }; /** * @doc property * @id DSProvider.properties:defaults.deserialize * @name DSProvider.properties:defaults.deserialize * @description * Your server might return a custom response object instead of the plain POJO payload. Use `deserialize` to * pull the payload out of your response object so angular-data can use it. * * ## Example: * ```js * DSProvider.defaults.deserialize = function (resourceName, data) { * return data ? data.payload : data; * }; * ``` * * @param {string} resourceName The name of the resource to deserialize. * @param {object} data Response object from `$http()`. * @returns {*} By default returns `data.data`. */ Defaults.prototype.deserialize = function (resourceName, data) { return data ? (data.data ? data.data : data) : data; }; /** * @doc property * @id DSProvider.properties:defaults.events * @name DSProvider.properties:defaults.events * @description * Whether to broadcast, emit, or disable DS events on the `$rootScope`. * * Possible values are: `"broadcast"`, `"emit"`, `"none"`. * * `"broadcast"` events will be [broadcasted](https://code.angularjs.org/1.2.22/docs/api/ng/type/$rootScope.Scope#$broadcast) on the `$rootScope`. * * `"emit"` events will be [emitted](https://code.angularjs.org/1.2.22/docs/api/ng/type/$rootScope.Scope#$emit) on the `$rootScope`. * * `"none"` events will be will neither be broadcasted nor emitted. * * Current events are `"DS.inject"` and `"DS.eject"`. * * Overridable per resource. */ Defaults.prototype.events = 'broadcast'; /** * @doc function * @id DSProvider * @name DSProvider */ function DSProvider() { /** * @doc property * @id DSProvider.properties:defaults * @name defaults * @description * See the [configuration guide](/documentation/guide/configure/global). * * Properties: * * - `{string}` - `baseUrl` - The url relative to which all AJAX requests will be made. * - `{string}` - `idAttribute` - Default: `"id"` - The attribute that specifies the primary key for resources. * - `{string}` - `defaultAdapter` - Default: `"DSHttpAdapter"` * - `{string}` - `events` - Default: `"broadcast"` [DSProvider.defaults.events](/documentation/api/angular-data/DSProvider.properties:defaults.events) * - `{function}` - `filter` - Default: See [angular-data query language](/documentation/guide/queries/custom). * - `{function}` - `beforeValidate` - See [DSProvider.defaults.beforeValidate](/documentation/api/angular-data/DSProvider.properties:defaults.beforeValidate). Default: No-op * - `{function}` - `validate` - See [DSProvider.defaults.validate](/documentation/api/angular-data/DSProvider.properties:defaults.validate). Default: No-op * - `{function}` - `afterValidate` - See [DSProvider.defaults.afterValidate](/documentation/api/angular-data/DSProvider.properties:defaults.afterValidate). Default: No-op * - `{function}` - `beforeCreate` - See [DSProvider.defaults.beforeCreate](/documentation/api/angular-data/DSProvider.properties:defaults.beforeCreate). Default: No-op * - `{function}` - `afterCreate` - See [DSProvider.defaults.afterCreate](/documentation/api/angular-data/DSProvider.properties:defaults.afterCreate). Default: No-op * - `{function}` - `beforeUpdate` - See [DSProvider.defaults.beforeUpdate](/documentation/api/angular-data/DSProvider.properties:defaults.beforeUpdate). Default: No-op * - `{function}` - `afterUpdate` - See [DSProvider.defaults.afterUpdate](/documentation/api/angular-data/DSProvider.properties:defaults.afterUpdate). Default: No-op * - `{function}` - `beforeDestroy` - See [DSProvider.defaults.beforeDestroy](/documentation/api/angular-data/DSProvider.properties:defaults.beforeDestroy). Default: No-op * - `{function}` - `afterDestroy` - See [DSProvider.defaults.afterDestroy](/documentation/api/angular-data/DSProvider.properties:defaults.afterDestroy). Default: No-op * - `{function}` - `afterInject` - See [DSProvider.defaults.afterInject](/documentation/api/angular-data/DSProvider.properties:defaults.afterInject). Default: No-op * - `{function}` - `beforeInject` - See [DSProvider.defaults.beforeInject](/documentation/api/angular-data/DSProvider.properties:defaults.beforeInject). Default: No-op * - `{function}` - `serialize` - See [DSProvider.defaults.serialize](/documentation/api/angular-data/DSProvider.properties:defaults.serialize). Default: No-op * - `{function}` - `deserialize` - See [DSProvider.defaults.deserialize](/documentation/api/angular-data/DSProvider.properties:defaults.deserialize). Default: No-op */ var defaults = this.defaults = new Defaults(); this.$get = [ '$rootScope', '$log', '$q', 'DSHttpAdapter', 'DSLocalStorageAdapter', 'DSUtils', 'DSErrors', function ($rootScope, $log, $q, DSHttpAdapter, DSLocalStorageAdapter, DSUtils, DSErrors) { var syncMethods = require('./sync_methods'); var asyncMethods = require('./async_methods'); var cache; try { cache = angular.injector(['angular-data.DSCacheFactory']).get('DSCacheFactory'); } catch (err) { $log.debug('DSCacheFactory is unavailable. Resorting to the lesser capabilities of $cacheFactory.'); cache = angular.injector(['ng']).get('$cacheFactory'); } /** * @doc interface * @id DS * @name DS * @description * Public data store interface. Consists of several properties and a number of methods. Injectable as `DS`. * * See the [guide](/documentation/guide/overview/index). */ var DS = { emit: function (definition, event) { var args = Array.prototype.slice.call(arguments, 2); args.unshift(definition.name); args.unshift('DS.' + event); definition.emit.apply(definition, args); if (definition.events === 'broadcast') { $rootScope.$broadcast.apply($rootScope, args); } else if (definition.events === 'emit') { $rootScope.$emit.apply($rootScope, args); } }, $rootScope: $rootScope, $log: $log, $q: $q, cacheFactory: cache, /** * @doc property * @id DS.properties:defaults * @name defaults * @description * Reference to [DSProvider.defaults](/documentation/api/api/DSProvider.properties:defaults). */ defaults: defaults, /*! * @doc property * @id DS.properties:store * @name store * @description * Meta data for each registered resource. */ store: {}, /*! * @doc property * @id DS.properties:definitions * @name definitions * @description * Registered resource definitions available to the data store. */ definitions: {}, /** * @doc property * @id DS.properties:adapters * @name adapters * @description * Registered adapters available to the data store. Object consists of key-values pairs where the key is * the name of the adapter and the value is the adapter itself. */ adapters: { DSHttpAdapter: DSHttpAdapter, DSLocalStorageAdapter: DSLocalStorageAdapter }, /** * @doc property * @id DS.properties:errors * @name errors * @description * References to the various [error types](/documentation/api/api/errors) used by angular-data. */ errors: DSErrors, /*! * @doc property * @id DS.properties:utils * @name utils * @description * Utility functions used internally by angular-data. */ utils: DSUtils }; DSUtils.deepFreeze(syncMethods); DSUtils.deepFreeze(asyncMethods); DSUtils.deepMixIn(DS, syncMethods); DSUtils.deepMixIn(DS, asyncMethods); DSUtils.deepFreeze(DS.errors); DSUtils.deepFreeze(DS.utils); DSHttpAdapter.DS = DS; DSLocalStorageAdapter.DS = DS; if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { $rootScope.$watch(function () { observe.Platform.performMicrotaskCheckpoint(); }); } return DS; } ]; } module.exports = DSProvider; },{"../../lib/observe-js/observe-js":1,"./async_methods":61,"./sync_methods":82}],68:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.bindAll(scope, expr, ' + resourceName + ', params[, cb]): '; } /** * @doc method * @id DS.sync methods:bindAll * @name bindAll * @description * Bind a collection of items in the data store to `scope` under the property specified by `expr` filtered by `params`. * * ## Signature: * ```js * DS.bindAll(scope, expr, resourceName, params[, cb]) * ``` * * ## Example: * * ```js * // bind the documents with ownerId of 5 to the 'docs' property of the $scope * var deregisterFunc = DS.bindAll($scope, 'docs', 'document', { * where: { * ownerId: 5 * } * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {object} scope The scope to bind to. * @param {string} expr An expression used to bind to the scope. Can be used to set nested keys, i.e. `"user.comments"`. * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} params Parameter object that is used in filtering the collection. Properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {function=} cb Optional callback executed on change. Signature: `cb(err, items)`. * * @returns {function} Scope $watch deregistration function. */ function bindAll(scope, expr, resourceName, params, cb) { var DS = this; var IA = DS.errors.IA; params = params || {}; if (!DS.utils.isObject(scope)) { throw new IA(errorPrefix(resourceName) + 'scope: Must be an object!'); } else if (!DS.utils.isString(expr)) { throw new IA(errorPrefix(resourceName) + 'expr: Must be a string!'); } else if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } try { return scope.$watch(function () { return DS.lastModified(resourceName); }, function () { var items = DS.filter(resourceName, params); DS.utils.set(scope, expr, items); if (cb) { cb(null, items); } }); } catch (err) { if (cb) { cb(err); } else { throw err; } } } module.exports = bindAll; },{}],69:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.bindOne(scope, expr, ' + resourceName + ', id[, cb]): '; } /** * @doc method * @id DS.sync methods:bindOne * @name bindOne * @description * Bind an item in the data store to `scope` under the property specified by `expr`. * * ## Signature: * ```js * DS.bindOne(scope, expr, resourceName, id[, cb]) * ``` * * ## Example: * * ```js * // bind the document with id 5 to the 'doc' property of the $scope * var deregisterFunc = DS.bindOne($scope, 'doc', 'document', 5); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {object} scope The scope to bind to. * @param {string} expr An expression used to bind to the scope. Can be used to set nested keys, i.e. `"user.profile"`. * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to bind. * @param {function=} cb Optional callback executed on change. Signature: `cb(err, item)`. * @returns {function} Scope $watch deregistration function. */ function bindOne(scope, expr, resourceName, id, cb) { var DS = this; var IA = DS.errors.IA; id = DS.utils.resolveId(DS.definitions[resourceName], id); if (!DS.utils.isObject(scope)) { throw new IA(errorPrefix(resourceName) + 'scope: Must be an object!'); } else if (!DS.utils.isString(expr)) { throw new IA(errorPrefix(resourceName) + 'expr: Must be a string!'); } else if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName) + 'id: Must be a string or a number!'); } try { return scope.$watch(function () { return DS.lastModified(resourceName, id); }, function () { var item = DS.get(resourceName, id); DS.utils.set(scope, expr, item); if (cb) { cb(null, item); } }); } catch (err) { if (cb) { cb(err); } else { throw err; } } } module.exports = bindOne; },{}],70:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.changeHistory(' + resourceName + ', id): '; } /** * @doc method * @id DS.sync methods:changeHistory * @name changeHistory * @description * Synchronously return the changeHistory of the item of the type specified by `resourceName` that has the primary key * specified by `id`. This object represents the history of changes in the item since the item was last injected or * re-injected (on save, update, etc.) into the data store. * * ## Signature: * ```js * DS.changeHistory(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * // You might have to do $scope.$apply() first * * DS.changeHistory('document', 5); // [{...}] Array of changes * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number=} id The primary key of the item for which to retrieve the changeHistory. * @returns {object} The changeHistory of the item of the type specified by `resourceName` with the primary key specified by `id`. */ function changeHistory(resourceName, id) { var DS = this; var DSUtils = DS.utils; var definition = DS.definitions[resourceName]; var resource = DS.store[resourceName]; id = DS.utils.resolveId(definition, id); if (resourceName && !DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (id && !DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName) + 'id: Must be a string or a number!'); } if (!definition.keepChangeHistory) { DS.$log.warn(errorPrefix(resourceName) + 'changeHistory is disabled for this resource!'); } else { if (resourceName) { var item = DS.get(resourceName, id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } } module.exports = changeHistory; },{}],71:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.changes(' + resourceName + ', id): '; } /** * @doc method * @id DS.sync methods:changes * @name changes * @description * Synchronously return the changes object of the item of the type specified by `resourceName` that has the primary key * specified by `id`. This object represents the diff between the item in its current state and the state of the item * the last time it was saved via an adapter. * * ## Signature: * ```js * DS.changes(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * // You might have to do $scope.$apply() first * * DS.changes('document', 5); // {...} Object describing changes * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item of the changes to retrieve. * @param {object=} options Optional configuration. Properties: * * - `{array=}` - `blacklist` - Array of strings or RegExp that specify fields that should be ignored when checking for changes. * * @returns {object} The changes of the item of the type specified by `resourceName` with the primary key specified by `id`. */ function changes(resourceName, id, options) { var DS = this; var DSUtils = DS.utils; var definition = DS.definitions[resourceName]; options = options || {}; id = DSUtils.resolveId(DS.definitions[resourceName], id); if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName) + 'id: Must be a string or a number!'); } else if (!DSUtils.isObject(options)) { throw new DS.errors.IA(errorPrefix(resourceName) + 'options: Must be an object!'); } options = DSUtils._(definition, options); var item = DS.get(resourceName, id); if (item) { DS.store[resourceName].observers[id].deliver(); var diff = DSUtils.diffObjectFromOldObject(item, DS.store[resourceName].previousAttributes[id], options.ignoredChanges); DSUtils.forEach(diff, function (changeset, name) { var toKeep = []; DSUtils.forEach(changeset, function (value, field) { if (!angular.isFunction(value)) { toKeep.push(field); } }); diff[name] = DSUtils.pick(diff[name], toKeep); }); DSUtils.forEach(DS.definitions[resourceName].relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return diff; } } module.exports = changes; },{}],72:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.compute(' + resourceName + ', instance): '; } function _compute(fn, field) { var _this = this; var args = []; angular.forEach(fn.deps, function (dep) { args.push(_this[dep]); }); // compute property this[field] = fn[fn.length - 1].apply(this, args); } /** * @doc method * @id DS.sync methods:compute * @name compute * @description * Force the given instance or the item with the given primary key to recompute its computed properties. * * ## Signature: * ```js * DS.compute(resourceName, instance) * ``` * * ## Example: * * ```js * var User = DS.defineResource({ * name: 'user', * computed: { * fullName: ['first', 'last', function (first, last) { * return first + ' ' + last; * }] * } * }); * * var user = User.createInstance({ first: 'John', last: 'Doe' }); * user.fullName; // undefined * * User.compute(user); * * user.fullName; // "John Doe" * * var user2 = User.inject({ id: 2, first: 'Jane', last: 'Doe' }); * user2.fullName; // undefined * * User.compute(1); * * user2.fullName; // "Jane Doe" * * // if you don't pass useClass: false then you can do: * var user3 = User.createInstance({ first: 'Sally', last: 'Doe' }); * user3.fullName; // undefined * user3.DSCompute(); * user3.fullName; // "Sally Doe" * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object|string|number} instance Instance or primary key of the instance (must be in the store) for which to recompute properties. * @returns {Object} The instance. */ function compute(resourceName, instance) { var DS = this; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; instance = DS.utils.resolveItem(DS.store[resourceName], instance); if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(instance) && !DS.utils.isString(instance) && !DS.utils.isNumber(instance)) { throw new IA(errorPrefix(resourceName) + 'instance: Must be an object, string or number!'); } if (DS.utils.isString(instance) || DS.utils.isNumber(instance)) { instance = DS.get(resourceName, instance); } DS.utils.forEach(definition.computed, function (fn, field) { _compute.call(instance, fn, field); }); return instance; } module.exports = { compute: compute, _compute: _compute }; },{}],73:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.createInstance(' + resourceName + '[, attrs][, options]): '; } /** * @doc method * @id DS.sync methods:createInstance * @name createInstance * @description * Return a new instance of the specified resource. * * ## Signature: * ```js * DS.createInstance(resourceName[, attrs][, options]) * ``` * * ## Example: * * ```js * var User = DS.defineResource({ * name: 'user', * methods: { * say: function () { * return 'hi'; * } * } * }); * * var user = User.createInstance(); * var user2 = DS.createInstance('user'); * * user instanceof User[User.class]; // true * user2 instanceof User[User.class]; // true * * user.say(); // hi * user2.say(); // hi * * var user3 = User.createInstance({ name: 'John' }, { useClass: false }); * var user4 = DS.createInstance('user', { name: 'John' }, { useClass: false }); * * user3; // { name: 'John' } * user3 instanceof User[User.class]; // false * * user4; // { name: 'John' } * user4 instanceof User[User.class]; // false * * user3.say(); // TypeError: undefined is not a function * user4.say(); // TypeError: undefined is not a function * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object=} attrs Optional attributes to mix in to the new instance. * @param {object=} options Optional configuration. Properties: * * - `{boolean=}` - `useClass` - Whether to wrap the injected item with the resource's instance constructor. * * @returns {object} The new instance. */ function createInstance(resourceName, attrs, options) { var DS = this; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; attrs = attrs || {}; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (attrs && !DS.utils.isObject(attrs)) { throw new IA(errorPrefix(resourceName) + 'attrs: Must be an object!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } if (!('useClass' in options)) { options.useClass = definition.useClass; } var item; if (options.useClass) { var Func = definition[definition['class']]; item = new Func(); } else { item = {}; } return DS.utils.deepMixIn(item, attrs); } module.exports = createInstance; },{}],74:[function(require,module,exports){ /*jshint evil:true*/ var errorPrefix = 'DS.defineResource(definition): '; function Resource(utils, options) { utils.deepMixIn(this, options); if ('endpoint' in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } } var instanceMethods = [ 'save', 'update', 'destroy', 'refresh', 'loadRelations', 'changeHistory', 'changes', 'hasChanges', 'lastModified', 'lastSaved', 'link', 'linkInverse', 'previous', 'unlinkInverse' ]; var methodsToProxy = [ 'bindAll', 'bindOne', 'changes', 'changeHistory', 'create', 'createInstance', 'destroy', 'destroyAll', 'digest', 'eject', 'ejectAll', 'filter', 'find', 'findAll', 'get', 'getAll', 'hasChanges', 'inject', 'lastModified', 'lastSaved', 'link', 'linkAll', 'linkInverse', 'loadRelations', 'previous', 'refresh', 'save', 'update', 'updateAll' ]; /** * @doc method * @id DS.sync methods:defineResource * @name defineResource * @description * Define a resource and register it with the data store. * * ## Signature: * ```js * DS.defineResource(definition) * ``` * * ## Example: * * ```js * DS.defineResource({ * name: 'document', * idAttribute: '_id', * endpoint: '/documents * baseUrl: 'http://myapp.com/api', * beforeDestroy: function (resourceName attrs, cb) { * console.log('looks good to me'); * cb(null, attrs); * } * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * * @param {string|object} definition Name of resource or resource definition object: Properties: * * - `{string}` - `name` - The name by which this resource will be identified. * - `{string="id"}` - `idAttribute` - The attribute that specifies the primary key for this resource. * - `{string=}` - `endpoint` - The attribute that specifies the primary key for this resource. Default is the value of `name`. * - `{string=}` - `baseUrl` - The url relative to which all AJAX requests will be made. * - `{boolean=}` - `useClass` - Whether to use a wrapper class created from the ProperCase name of the resource. The wrapper will always be used for resources that have `methods` defined. * - `{boolean=}` - `keepChangeHistory` - Whether to keep a history of changes for items in the data store. Default: `false`. * - `{boolean=}` - `resetHistoryOnInject` - Whether to reset the history of changes for items when they are injected of re-injected into the data store. This will also reset an item's previous attributes. Default: `true`. * - `{function=}` - `defaultFilter` - Override the filtering used internally by `DS.filter` with you own function here. * - `{*=}` - `meta` - A property reserved for developer use. This will never be used by the API. * - `{object=}` - `methods` - If provided, items of this resource will be wrapped in a constructor function that is * empty save for the attributes in this option which will be mixed in to the constructor function prototype. Enabling * this feature for this resource will incur a slight performance penalty, but allows you to give custom behavior to what * are now "instances" of this resource. * - `{function=}` - `beforeValidate` - Lifecycle hook. Overrides global. Signature: `beforeValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `validate` - Lifecycle hook. Overrides global. Signature: `validate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterValidate` - Lifecycle hook. Overrides global. Signature: `afterValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeCreate` - Lifecycle hook. Overrides global. Signature: `beforeCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterCreate` - Lifecycle hook. Overrides global. Signature: `afterCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeUpdate` - Lifecycle hook. Overrides global. Signature: `beforeUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterUpdate` - Lifecycle hook. Overrides global. Signature: `afterUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeDestroy` - Lifecycle hook. Overrides global. Signature: `beforeDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterDestroy` - Lifecycle hook. Overrides global. Signature: `afterDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeInject` - Lifecycle hook. Overrides global. Signature: `beforeInject(resourceName, attrs)`. * - `{function=}` - `afterInject` - Lifecycle hook. Overrides global. Signature: `afterInject(resourceName, attrs)`. * - `{function=}` - `serialize` - Serialization hook. Overrides global. Signature: `serialize(resourceName, attrs)`. * - `{function=}` - `deserialize` - Deserialization hook. Overrides global. Signature: `deserialize(resourceName, attrs)`. * * See [DSProvider.defaults](/documentation/api/angular-data/DSProvider.properties:defaults). */ function defineResource(definition) { var DS = this; var DSUtils = DS.utils; var definitions = DS.definitions; var IA = DS.errors.IA; if (DSUtils.isString(definition)) { definition = definition.replace(/\s/gi, ''); definition = { name: definition }; } var defName = definition ? definition.name : undefined; if (!DSUtils.isObject(definition)) { throw new IA(errorPrefix + 'definition: Must be an object!'); } else if (!DSUtils.isString(defName)) { throw new IA(errorPrefix + 'definition.name: Must be a string!'); } else if (definition.idAttribute && !DSUtils.isString(definition.idAttribute)) { throw new IA(errorPrefix + 'definition.idAttribute: Must be a string!'); } else if (definition.endpoint && !DSUtils.isString(definition.endpoint)) { throw new IA(errorPrefix + 'definition.endpoint: Must be a string!'); } else if (DS.store[defName]) { throw new DS.errors.R(errorPrefix + defName + ' is already registered!'); } try { // Inherit from global defaults Resource.prototype = DS.defaults; definitions[defName] = new Resource(DSUtils, definition); var def = definitions[defName]; // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; DSUtils.forEach(def.relations, function (relatedModels, type) { DSUtils.forEach(relatedModels, function (defs, relationName) { if (!DSUtils.isArray(defs)) { relatedModels[relationName] = [defs]; } DSUtils.forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.name; def.relationList.push(d); def.relationFields.push(d.localField); }); }); }); if (def.relations.belongsTo) { DSUtils.forEach(def.relations.belongsTo, function (relatedModel, modelName) { DSUtils.forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; } }); }); } DSUtils.deepFreeze(def.relations); DSUtils.deepFreeze(def.relationList); } def.getEndpoint = function (attrs, options) { options = DSUtils.deepMixIn({}, options); var parent = this.parent; var parentKey = this.parentKey; var item; var endpoint; var thisEndpoint = options.endpoint || this.endpoint; delete options.endpoint; options = options || {}; options.params = options.params || {}; if (parent && parentKey && definitions[parent] && options.params[parentKey] !== false) { if (DSUtils.isNumber(attrs) || DSUtils.isString(attrs)) { item = DS.get(this.name, attrs); } if (DSUtils.isObject(attrs) && parentKey in attrs) { delete options.params[parentKey]; endpoint = DSUtils.makePath(definitions[parent].getEndpoint(attrs, options), attrs[parentKey], thisEndpoint); } else if (item && parentKey in item) { delete options.params[parentKey]; endpoint = DSUtils.makePath(definitions[parent].getEndpoint(attrs, options), item[parentKey], thisEndpoint); } else if (options && options.params[parentKey]) { endpoint = DSUtils.makePath(definitions[parent].getEndpoint(attrs, options), options.params[parentKey], thisEndpoint); delete options.params[parentKey]; } } if (options.params[parentKey] === false) { delete options.params[parentKey]; } return endpoint || thisEndpoint; }; // Remove this in v0.11.0 and make a breaking change notice // the the `filter` option has been renamed to `defaultFilter` if (def.filter) { def.defaultFilter = def.filter; delete def.filter; } // Setup the cache var cache = DS.cacheFactory('DS.' + def.name, { maxAge: def.maxAge || null, recycleFreq: def.recycleFreq || 1000, cacheFlushInterval: def.cacheFlushInterval || null, deleteOnExpire: def.deleteOnExpire || 'none', onExpire: function (id) { var item = DS.eject(def.name, id); if (DSUtils.isFunction(def.onExpire)) { def.onExpire(id, item); } }, capacity: Number.MAX_VALUE, storageMode: 'memory', storageImpl: null, disabled: false, storagePrefix: 'DS.' + def.name }); // Create the wrapper class for the new resource def['class'] = DSUtils.pascalCase(defName); try { eval('function ' + def['class'] + '() {}'); def[def['class']] = eval(def['class']); } catch (e) { def[def['class']] = function () { }; } // Apply developer-defined methods if (def.methods) { DSUtils.deepMixIn(def[def['class']].prototype, def.methods); } // Prepare for computed properties if (def.computed) { DSUtils.forEach(def.computed, function (fn, field) { if (angular.isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { DS.$log.warn(errorPrefix + 'Computed property "' + field + '" conflicts with previously defined prototype method!'); } var deps; if (fn.length === 1) { var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/); deps = match[1].split(','); def.computed[field] = deps.concat(fn); fn = def.computed[field]; if (deps.length) { DS.$log.warn(errorPrefix + 'Use the computed property array syntax for compatibility with minified code!'); } } deps = fn.slice(0, fn.length - 1); angular.forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = DSUtils.filter(deps, function (dep) { return !!dep; }); }); def[def['class']].prototype.DSCompute = function () { return DS.compute(def.name, this); }; } DSUtils.forEach(instanceMethods, function (name) { def[def['class']].prototype['DS' + DSUtils.pascalCase(name)] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(this[def.idAttribute]); args.unshift(def.name); return DS[name].apply(DS, args); }; }); // Initialize store data for the new resource DS.store[def.name] = { collection: [], completedQueries: {}, pendingQueries: {}, index: cache, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; // Proxy DS methods with shorthand ones angular.forEach(methodsToProxy, function (name) { if (name === 'bindOne' || name === 'bindAll') { def[name] = function () { var args = Array.prototype.slice.call(arguments); args.splice(2, 0, def.name); return DS[name].apply(DS, args); }; } else { def[name] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(def.name); return DS[name].apply(DS, args); }; } }); def.beforeValidate = DS.$q.promisify(def.beforeValidate); def.validate = DS.$q.promisify(def.validate); def.afterValidate = DS.$q.promisify(def.afterValidate); def.beforeCreate = DS.$q.promisify(def.beforeCreate); def.afterCreate = DS.$q.promisify(def.afterCreate); def.beforeUpdate = DS.$q.promisify(def.beforeUpdate); def.afterUpdate = DS.$q.promisify(def.afterUpdate); def.beforeDestroy = DS.$q.promisify(def.beforeDestroy); def.afterDestroy = DS.$q.promisify(def.afterDestroy); // Mix-in events DSUtils.Events(def); return def; } catch (err) { DS.$log.error(err); delete definitions[defName]; delete DS.store[defName]; throw err; } } module.exports = defineResource; },{}],75:[function(require,module,exports){ var observe = require('../../../lib/observe-js/observe-js'); /** * @doc method * @id DS.sync methods:digest * @name digest * @description * Trigger a digest loop that checks for changes and updates the `lastModified` timestamp if an object has changed. * Anything $watching `DS.lastModified(...)` will detect the updated timestamp and execute the callback function. If * your browser supports `Object.observe` then this function has no effect. * * ## Signature: * ```js * DS.digest() * ``` * * ## Example: * * ```js * Works like $scope.$apply() * ``` * */ function digest() { if (!this.$rootScope.$$phase) { this.$rootScope.$apply(function () { observe.Platform.performMicrotaskCheckpoint(); }); } else { observe.Platform.performMicrotaskCheckpoint(); } } module.exports = digest; },{"../../../lib/observe-js/observe-js":1}],76:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.eject(' + resourceName + ', ' + id + '): '; } function _eject(definition, resource, id, options) { var item; var DS = this; var found = false; for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { item = resource.collection[i]; found = true; break; } } if (found) { this.unlinkInverse(definition.name, id); resource.collection.splice(i, 1); resource.observers[id].close(); delete resource.observers[id]; resource.index.remove(id); delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; DS.utils.forEach(resource.changeHistories[id], function (changeRecord) { DS.utils.remove(resource.changeHistory, changeRecord); }); delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; resource.collectionModified = this.utils.updateTimestamp(resource.collectionModified); if (options.notify) { this.emit(definition, 'eject', item); } return item; } } /** * @doc method * @id DS.sync methods:eject * @name eject * @description * Eject the item of the specified type that has the given primary key from the data store. Ejection only removes items * from the data store and does not attempt to destroy items via an adapter. * * ## Signature: * ```js * DS.eject(resourceName[, id]) * ``` * * ## Example: * * ```js * DS.get('document', 45); // { title: 'How to Cook', id: 45 } * * DS.eject('document', 45); * * DS.get('document', 45); // undefined * ``` * * ```js * $rootScope.$on('DS.eject', function ($event, resourceName, ejected) {...}); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to eject. * @param {object=} options Optional configuration. * @returns {object} A reference to the item that was ejected from the data store. */ function eject(resourceName, id, options) { var DS = this; var definition = DS.definitions[resourceName]; options = options || {}; id = DS.utils.resolveId(definition, id); if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } var resource = DS.store[resourceName]; var ejected; if (!('notify' in options)) { options.notify = definition.notify; } if (!DS.$rootScope.$$phase) { DS.$rootScope.$apply(function () { ejected = _eject.call(DS, definition, resource, id, options); }); } else { ejected = _eject.call(DS, definition, resource, id, options); } return ejected; } module.exports = eject; },{}],77:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.ejectAll(' + resourceName + '[, params]): '; } function _ejectAll(definition, resource, params, options) { var DS = this; var queryHash = DS.utils.toJson(params); var items = DS.filter(definition.name, params); var ids = DS.utils.toLookup(items, definition.idAttribute); angular.forEach(ids, function (item, id) { DS.eject(definition.name, id); }); delete resource.completedQueries[queryHash]; resource.collectionModified = DS.utils.updateTimestamp(resource.collectionModified); if (options.notify) { DS.emit(definition, 'eject', items); } return items; } /** * @doc method * @id DS.sync methods:ejectAll * @name ejectAll * @description * Eject all matching items of the specified type from the data store. Ejection only removes items from the data store * and does not attempt to destroy items via an adapter. * * ## Signature: * ```js * DS.ejectAll(resourceName[, params]) * ``` * * ## Example: * * ```js * DS.get('document', 45); // { title: 'How to Cook', id: 45 } * * DS.eject('document', 45); * * DS.get('document', 45); // undefined * ``` * * Eject all items of the specified type that match the criteria from the data store. * * ```js * DS.filter('document'); // [ { title: 'How to Cook', id: 45, author: 'John Anderson' }, * // { title: 'How to Eat', id: 46, author: 'Sally Jane' } ] * * DS.ejectAll('document', { where: { author: 'Sally Jane' } }); * * DS.filter('document'); // [ { title: 'How to Cook', id: 45, author: 'John Anderson' } ] * ``` * * Eject all items of the specified type from the data store. * * ```js * DS.filter('document'); // [ { title: 'How to Cook', id: 45, author: 'John Anderson' }, * // { title: 'How to Eat', id: 46, author: 'Sally Jane' } ] * * DS.ejectAll('document'); * * DS.filter('document'); // [ ] * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} params Parameter object that is used to filter items. Properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. * * @returns {array} The items that were ejected from the data store. */ function ejectAll(resourceName, params, options) { var DS = this; var definition = DS.definitions[resourceName]; params = params || {}; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(params)) { throw new DS.errors.IA(errorPrefix(resourceName) + 'params: Must be an object!'); } var resource = DS.store[resourceName]; var ejected; if (DS.utils.isEmpty(params)) { resource.completedQueries = {}; } if (!('notify' in options)) { options.notify = definition.notify; } if (!DS.$rootScope.$$phase) { DS.$rootScope.$apply(function () { ejected = _ejectAll.call(DS, definition, resource, params, options); }); } else { ejected = _ejectAll.call(DS, definition, resource, params, options); } return ejected; } module.exports = ejectAll; },{}],78:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.filter(' + resourceName + '[, params][, options]): '; } /** * @doc method * @id DS.sync methods:filter * @name filter * @description * Synchronously filter items in the data store of the type specified by `resourceName`. * * ## Signature: * ```js * DS.filter(resourceName[, params][, options]) * ``` * * ## Example: * * For many examples see the [tests for DS.filter](https://github.com/jmdobry/angular-data/blob/master/test/integration/datastore/sync_methods/filter.test.js). * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object=} params Parameter object that is used to filter items. Properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Properties: * * - `{boolean=}` - `loadFromServer` - Send the query to server if it has not been sent yet. Default: `false`. * - `{boolean=}` - `allowSimpleWhere` - Treat top-level fields on the `params` argument as simple "where" equality clauses. Default: `true`. * * @returns {array} The filtered collection of items of the type specified by `resourceName`. */ function filter(resourceName, params, options) { var DS = this; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (params && !DS.utils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } var resource = DS.store[resourceName]; // Protect against null params = params || {}; if ('allowSimpleWhere' in options) { options.allowSimpleWhere = !!options.allowSimpleWhere; } else { options.allowSimpleWhere = true; } var queryHash = DS.utils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started DS.findAll(resourceName, params, options); } } return definition.defaultFilter.call(DS, resource.collection, resourceName, params, options); } module.exports = filter; },{}],79:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.get(' + resourceName + ', ' + id + '): '; } /** * @doc method * @id DS.sync methods:get * @name get * @description * Synchronously return the resource with the given id. The data store will forward the request to an adapter if * `loadFromServer` is `true` in the options hash. * * ## Signature: * ```js * DS.get(resourceName, id[, options]) * ``` * * ## Example: * * ```js * DS.get('document', 5'); // { author: 'John Anderson', id: 5 } * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to retrieve. * @param {object=} options Optional configuration. Also passed along to `DS.find` if `loadFromServer` is `true`. Properties: * * - `{boolean=}` - `loadFromServer` - Send the query to server if it has not been sent yet. Default: `false`. * * @returns {object} The item of the type specified by `resourceName` with the primary key specified by `id`. */ function get(resourceName, id, options) { var DS = this; var IA = DS.errors.IA; options = options || {}; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName, id) + 'options: Must be an object!'); } // cache miss, request resource from server var item = DS.store[resourceName].index.get(id); if (!item && options.loadFromServer) { DS.find(resourceName, id, options).then(null, function (err) { return DS.$q.reject(err); }); } // return resource from cache return item; } module.exports = get; },{}],80:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.getAll(' + resourceName + '[, ids]): '; } /** * @doc method * @id DS.sync methods:getAll * @name getAll * @description * Synchronously return all items of the given resource, or optionally, a subset based on the given primary keys. * * ## Signature: * ```js * DS.getAll(resourceName[, ids]) * ``` * * ## Example: * * ```js * DS.getAll('document'); // [{ author: 'John Anderson', id: 5 }] * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {array} ids Optional list of primary keys by which to filter the results. * * @returns {array} The items of the type specified by `resourceName`. */ function getAll(resourceName, ids) { var DS = this; var IA = DS.errors.IA; var resource = DS.store[resourceName]; var collection = []; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (ids && !DS.utils.isArray(ids)) { throw new IA(errorPrefix(resourceName, ids) + 'ids: Must be an array!'); } if (DS.utils.isArray(ids)) { for (var i = 0; i < ids.length; i++) { if (resource.index.get(ids[i])) { collection.push(resource.index.get(ids[i])); } } } else { collection = resource.collection.slice(); } return collection; } module.exports = getAll; },{}],81:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.hasChanges(' + resourceName + ', ' + id + '): '; } function diffIsEmpty(utils, diff) { return !(utils.isEmpty(diff.added) && utils.isEmpty(diff.removed) && utils.isEmpty(diff.changed)); } /** * @doc method * @id DS.sync methods:hasChanges * @name hasChanges * @description * Synchronously return whether object of the item of the type specified by `resourceName` that has the primary key * specified by `id` has changes. * * ## Signature: * ```js * DS.hasChanges(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * // You may have to do $scope.$apply() first * * DS.hasChanges('document', 5); // true * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item. * @returns {boolean} Whether the item of the type specified by `resourceName` with the primary key specified by `id` has changes. */ function hasChanges(resourceName, id) { var DS = this; id = DS.utils.resolveId(DS.definitions[resourceName], id); if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } // return resource from cache if (DS.get(resourceName, id)) { return diffIsEmpty(DS.utils, DS.changes(resourceName, id)); } else { return false; } } module.exports = hasChanges; },{}],82:[function(require,module,exports){ module.exports = { /** * @doc method * @id DS.sync methods:bindOne * @name bindOne * @methodOf DS * @description * See [DS.bindOne](/documentation/api/api/DS.sync methods:bindOne). */ bindOne: require('./bindOne'), /** * @doc method * @id DS.sync methods:bindAll * @name bindAll * @methodOf DS * @description * See [DS.bindAll](/documentation/api/api/DS.sync methods:bindAll). */ bindAll: require('./bindAll'), /** * @doc method * @id DS.sync methods:changes * @name changes * @methodOf DS * @description * See [DS.changes](/documentation/api/api/DS.sync methods:changes). */ changes: require('./changes'), /** * @doc method * @id DS.sync methods:changeHistory * @name changeHistory * @methodOf DS * @description * See [DS.changeHistory](/documentation/api/api/DS.sync methods:changeHistory). */ changeHistory: require('./changeHistory'), /** * @doc method * @id DS.sync methods:compute * @name compute * @methodOf DS * @description * See [DS.compute](/documentation/api/api/DS.sync methods:compute). */ compute: require('./compute').compute, /** * @doc method * @id DS.sync methods:createInstance * @name createInstance * @methodOf DS * @description * See [DS.createInstance](/documentation/api/api/DS.sync methods:createInstance). */ createInstance: require('./createInstance'), /** * @doc method * @id DS.sync methods:defineResource * @name defineResource * @methodOf DS * @description * See [DS.defineResource](/documentation/api/api/DS.sync methods:defineResource). */ defineResource: require('./defineResource'), /** * @doc method * @id DS.sync methods:digest * @name digest * @methodOf DS * @description * See [DS.digest](/documentation/api/api/DS.sync methods:digest). */ digest: require('./digest'), /** * @doc method * @id DS.sync methods:eject * @name eject * @methodOf DS * @description * See [DS.eject](/documentation/api/api/DS.sync methods:eject). */ eject: require('./eject'), /** * @doc method * @id DS.sync methods:ejectAll * @name ejectAll * @methodOf DS * @description * See [DS.ejectAll](/documentation/api/api/DS.sync methods:ejectAll). */ ejectAll: require('./ejectAll'), /** * @doc method * @id DS.sync methods:filter * @name filter * @methodOf DS * @description * See [DS.filter](/documentation/api/api/DS.sync methods:filter). */ filter: require('./filter'), /** * @doc method * @id DS.sync methods:get * @name get * @methodOf DS * @description * See [DS.get](/documentation/api/api/DS.sync methods:get). */ get: require('./get'), /** * @doc method * @id DS.sync methods:getAll * @name getAll * @methodOf DS * @description * See [DS.getAll](/documentation/api/api/DS.sync methods:getAll). */ getAll: require('./getAll'), /** * @doc method * @id DS.sync methods:hasChanges * @name hasChanges * @methodOf DS * @description * See [DS.hasChanges](/documentation/api/api/DS.sync methods:hasChanges). */ hasChanges: require('./hasChanges'), /** * @doc method * @id DS.sync methods:inject * @name inject * @methodOf DS * @description * See [DS.inject](/documentation/api/api/DS.sync methods:inject). */ inject: require('./inject'), /** * @doc method * @id DS.sync methods:lastModified * @name lastModified * @methodOf DS * @description * See [DS.lastModified](/documentation/api/api/DS.sync methods:lastModified). */ lastModified: require('./lastModified'), /** * @doc method * @id DS.sync methods:lastSaved * @name lastSaved * @methodOf DS * @description * See [DS.lastSaved](/documentation/api/api/DS.sync methods:lastSaved). */ lastSaved: require('./lastSaved'), /** * @doc method * @id DS.sync methods:link * @name link * @methodOf DS * @description * See [DS.link](/documentation/api/api/DS.sync methods:link). */ link: require('./link'), /** * @doc method * @id DS.sync methods:linkAll * @name linkAll * @methodOf DS * @description * See [DS.linkAll](/documentation/api/api/DS.sync methods:linkAll). */ linkAll: require('./linkAll'), /** * @doc method * @id DS.sync methods:linkInverse * @name linkInverse * @methodOf DS * @description * See [DS.linkInverse](/documentation/api/api/DS.sync methods:linkInverse). */ linkInverse: require('./linkInverse'), /** * @doc method * @id DS.sync methods:previous * @name previous * @methodOf DS * @description * See [DS.previous](/documentation/api/api/DS.sync methods:previous). */ previous: require('./previous'), /** * @doc method * @id DS.sync methods:unlinkInverse * @name unlinkInverse * @methodOf DS * @description * See [DS.unlinkInverse](/documentation/api/api/DS.sync methods:unlinkInverse). */ unlinkInverse: require('./unlinkInverse') }; },{"./bindAll":68,"./bindOne":69,"./changeHistory":70,"./changes":71,"./compute":72,"./createInstance":73,"./defineResource":74,"./digest":75,"./eject":76,"./ejectAll":77,"./filter":78,"./get":79,"./getAll":80,"./hasChanges":81,"./inject":83,"./lastModified":84,"./lastSaved":85,"./link":86,"./linkAll":87,"./linkInverse":88,"./previous":89,"./unlinkInverse":90}],83:[function(require,module,exports){ var observe = require('../../../lib/observe-js/observe-js'); var _compute = require('./compute')._compute; function errorPrefix(resourceName) { return 'DS.inject(' + resourceName + ', attrs[, options]): '; } function _inject(definition, resource, attrs, options) { var DS = this; var DSUtils = DS.utils; var $log = DS.$log; function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item; var innerId = (oldValueFn && oldValueFn(definition.idAttribute)) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; DSUtils.forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); if (!DSUtils.isEmpty(added) || !DSUtils.isEmpty(removed) || !DSUtils.isEmpty(changed) || firstTime) { item = DS.get(definition.name, innerId); resource.modified[innerId] = DSUtils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (definition.keepChangeHistory) { var changeRecord = { resourceName: definition.name, target: item, added: added, removed: removed, changed: changed, timestamp: resource.modified[innerId] }; resource.changeHistories[innerId].push(changeRecord); resource.changeHistory.push(changeRecord); } } if (definition.computed) { item = item || DS.get(definition.name, innerId); DSUtils.forEach(definition.computed, function (fn, field) { var compute = false; // check if required fields changed angular.forEach(fn.deps, function (dep) { if (dep in added || dep in removed || dep in changed || !(field in item)) { compute = true; } }); compute = compute || !fn.deps.length; if (compute) { _compute.call(item, fn, field); } }); } if (definition.relations) { item = item || DS.get(definition.name, innerId); DSUtils.forEach(definition.relationList, function (def) { if (item[def.localField] && (def.localKey in added || def.localKey in removed || def.localKey in changed)) { DS.link(definition.name, item[definition.idAttribute], [def.relation]); } }); } if (definition.idAttribute in changed) { $log.error('Doh! You just changed the primary key of an object! ' + 'I don\'t know how to handle this yet, so your data for the "' + definition.name + '" resource is now in an undefined (probably broken) state.'); } } var injected; if (DSUtils.isArray(attrs)) { injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(DS, definition, resource, attrs[i], options)); } } else { // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; if (c && c[idA]) { var args = []; angular.forEach(c[idA].deps, function (dep) { args.push(attrs[dep]); }); attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args); } if (!(idA in attrs)) { var error = new DS.errors.R(errorPrefix(definition.name) + 'attrs: Must contain the property specified by `idAttribute`!'); $log.error(error); throw error; } else { try { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = DS.definitions[relationName]; var toInject = attrs[def.localField]; if (toInject) { if (!relationDef) { throw new DS.errors.R(definition.name + 'relation is defined but the resource is not!'); } if (DSUtils.isArray(toInject)) { var items = []; DSUtils.forEach(toInject, function (toInjectItem) { if (toInjectItem !== DS.store[relationName][toInjectItem[relationDef.idAttribute]]) { try { var injectedItem = DS.inject(relationName, toInjectItem, options); if (def.foreignKey) { injectedItem[def.foreignKey] = attrs[definition.idAttribute]; } items.push(injectedItem); } catch (err) { DS.$log.error(errorPrefix(definition.name) + 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!', err); } } }); attrs[def.localField] = items; } else { if (toInject !== DS.store[relationName][toInject[relationDef.idAttribute]]) { try { attrs[def.localField] = DS.inject(relationName, attrs[def.localField], options); if (def.foreignKey) { attrs[def.localField][def.foreignKey] = attrs[definition.idAttribute]; } } catch (err) { DS.$log.error(errorPrefix(definition.name) + 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!', err); } } } } }); definition.beforeInject(definition.name, attrs); var id = attrs[idA]; var item = DS.get(definition.name, id); var initialLastModified = item ? resource.modified[id] : 0; if (!item) { if (options.useClass) { if (attrs instanceof definition[definition['class']]) { item = attrs; } else { item = new definition[definition['class']](); } } else { item = {}; } resource.previousAttributes[id] = angular.copy(attrs); DSUtils.deepMixIn(item, attrs); resource.collection.push(item); resource.changeHistories[id] = []; resource.observers[id] = new observe.ObjectObserver(item); resource.observers[id].open(_react, item); resource.index.put(id, item); _react.call(item, {}, {}, {}, null, true); } else { DSUtils.deepMixIn(item, attrs); if (definition.resetHistoryOnInject) { resource.previousAttributes[id] = {}; DSUtils.deepMixIn(resource.previousAttributes[id], attrs); if (resource.changeHistories[id].length) { DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (typeof resource.index.touch === 'function') { resource.index.touch(id); } else { resource.index.put(id, resource.index.get(id)); } resource.observers[id].deliver(); } resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? DSUtils.updateTimestamp(resource.modified[id]) : resource.modified[id]; definition.afterInject(definition.name, item); injected = item; } catch (err) { $log.error(err); $log.error('inject failed!', definition.name, attrs); } } } return injected; } function _link(definition, injected, options) { var DS = this; DS.utils.forEach(definition.relationList, function (def) { if (options.findBelongsTo && def.type === 'belongsTo' && injected[definition.idAttribute]) { DS.link(definition.name, injected[definition.idAttribute], [def.relation]); } else if ((options.findHasMany && def.type === 'hasMany') || (options.findHasOne && def.type === 'hasOne')) { DS.link(definition.name, injected[definition.idAttribute], [def.relation]); } }); } /** * @doc method * @id DS.sync methods:inject * @name inject * @description * Inject the given item into the data store as the specified type. If `attrs` is an array, inject each item into the * data store. Injecting an item into the data store does not save it to the server. Emits a `"DS.inject"` event. * * ## Signature: * ```js * DS.inject(resourceName, attrs[, options]) * ``` * * ## Examples: * * ```js * DS.get('document', 45); // undefined * * DS.inject('document', { title: 'How to Cook', id: 45 }); * * DS.get('document', 45); // { title: 'How to Cook', id: 45 } * ``` * * Inject a collection into the data store: * * ```js * DS.filter('document'); // [ ] * * DS.inject('document', [ { title: 'How to Cook', id: 45 }, { title: 'How to Eat', id: 46 } ]); * * DS.filter('document'); // [ { title: 'How to Cook', id: 45 }, { title: 'How to Eat', id: 46 } ] * ``` * * ```js * $rootScope.$on('DS.inject', function ($event, resourceName, injected) {...}); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object|array} attrs The item or collection of items to inject into the data store. * @param {object=} options The item or collection of items to inject into the data store. Properties: * * - `{boolean=}` - `useClass` - Whether to wrap the injected item with the resource's instance constructor. * - `{boolean=}` - `findBelongsTo` - Find and attach any existing "belongsTo" relationships to the newly injected item. Potentially expensive if enabled. Default: `false`. * - `{boolean=}` - `findHasMany` - Find and attach any existing "hasMany" relationships to the newly injected item. Potentially expensive if enabled. Default: `false`. * - `{boolean=}` - `findHasOne` - Find and attach any existing "hasOne" relationships to the newly injected item. Potentially expensive if enabled. Default: `false`. * - `{boolean=}` - `linkInverse` - Look in the data store for relations of the injected item(s) and update their links to the injected. Potentially expensive if enabled. Default: `false`. * * @returns {object|array} A reference to the item that was injected into the data store or an array of references to * the items that were injected into the data store. */ function inject(resourceName, attrs, options) { var DS = this; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(attrs) && !DS.utils.isArray(attrs)) { throw new IA(errorPrefix(resourceName) + 'attrs: Must be an object or an array!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } var resource = DS.store[resourceName]; var injected; if (!('useClass' in options)) { options.useClass = definition.useClass; } if (!('notify' in options)) { options.notify = definition.notify; } if (!DS.$rootScope.$$phase) { DS.$rootScope.$apply(function () { injected = _inject.call(DS, definition, resource, attrs, options); resource.collectionModified = DS.utils.updateTimestamp(resource.collectionModified); }); } else { injected = _inject.call(DS, definition, resource, attrs, options); resource.collectionModified = DS.utils.updateTimestamp(resource.collectionModified); } if (options.linkInverse && typeof options.linkInverse === 'boolean') { if (DS.utils.isArray(injected)) { if (injected.length) { DS.linkInverse(definition.name, injected[0][definition.idAttribute]); } } else { DS.linkInverse(definition.name, injected[definition.idAttribute]); } } if (DS.utils.isArray(injected)) { DS.utils.forEach(injected, function (injectedI) { _link.call(DS, definition, injectedI, options); }); } else { _link.call(DS, definition, injected, options); } if (options.notify) { DS.emit(definition, 'inject', injected); } return injected; } module.exports = inject; },{"../../../lib/observe-js/observe-js":1,"./compute":72}],84:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.lastModified(' + resourceName + '[, ' + id + ']): '; } /** * @doc method * @id DS.sync methods:lastModified * @name lastModified * @description * Return the timestamp of the last time either the collection for `resourceName` or the item of type `resourceName` * with the given primary key was modified. * * ## Signature: * ```js * DS.lastModified(resourceName[, id]) * ``` * * ## Example: * * ```js * DS.lastModified('document', 5); // undefined * * DS.find('document', 5).then(function (document) { * DS.lastModified('document', 5); // 1234235825494 * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number=} id The primary key of the item to remove. * @returns {number} The timestamp of the last time either the collection for `resourceName` or the item of type * `resourceName` with the given primary key was modified. */ function lastModified(resourceName, id) { var DS = this; var resource = DS.store[resourceName]; id = DS.utils.resolveId(DS.definitions[resourceName], id); if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (id && !DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; } module.exports = lastModified; },{}],85:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.lastSaved(' + resourceName + '[, ' + id + ']): '; } /** * @doc method * @id DS.sync methods:lastSaved * @name lastSaved * @description * Return the timestamp of the last time either the collection for `resourceName` or the item of type `resourceName` * with the given primary key was saved via an async adapter. * * ## Signature: * ```js * DS.lastSaved(resourceName[, id]) * ``` * * ## Example: * * ```js * DS.lastModified('document', 5); // undefined * DS.lastSaved('document', 5); // undefined * * DS.find('document', 5).then(function (document) { * DS.lastModified('document', 5); // 1234235825494 * DS.lastSaved('document', 5); // 1234235825494 * * document.author = 'Sally'; * * // You may have to call $scope.$apply() first * * DS.lastModified('document', 5); // 1234304985344 - something different * DS.lastSaved('document', 5); // 1234235825494 - still the same * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item for which to retrieve the lastSaved timestamp. * @returns {number} The timestamp of the last time the item of type `resourceName` with the given primary key was saved. */ function lastSaved(resourceName, id) { var DS = this; var resource = DS.store[resourceName]; id = DS.utils.resolveId(DS.definitions[resourceName], id); if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; } module.exports = lastSaved; },{}],86:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.link(' + resourceName + ', id[, relations]): '; } function _link(definition, linked, relations) { var DS = this; DS.utils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DS.utils.contains(relations, relationName)) { return; } var params = {}; if (def.type === 'belongsTo') { var parent = linked[def.localKey] ? DS.get(relationName, linked[def.localKey]) : null; if (parent) { linked[def.localField] = parent; } } else if (def.type === 'hasMany') { params[def.foreignKey] = linked[definition.idAttribute]; linked[def.localField] = DS.defaults.constructor.prototype.defaultFilter.call(DS, DS.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.type === 'hasOne') { params[def.foreignKey] = linked[definition.idAttribute]; var children = DS.defaults.constructor.prototype.defaultFilter.call(DS, DS.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { linked[def.localField] = children[0]; } } }); } /** * @doc method * @id DS.sync methods:link * @name link * @description * Find relations of the item with the given primary key that are already in the data store and link them to the item. * * ## Signature: * ```js * DS.link(resourceName, id[, relations]) * ``` * * ## Examples: * * Assume `user` has `hasMany` relationships to `post` and `comment`. * ```js * DS.get('user', 1); // { name: 'John', id: 1 } * * // link posts * DS.link('user', 1, ['post']); * * DS.get('user', 1); // { name: 'John', id: 1, posts: [...] } * * // link all relations * DS.link('user', 1); * * DS.get('user', 1); // { name: 'John', id: 1, posts: [...], comments: [...] } * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item for to link relations. * @param {array=} relations The relations to be linked. If not provided then all relations will be linked. Default: `[]`. * @returns {object|array} A reference to the item with its linked relations. */ function link(resourceName, id, relations) { var DS = this; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; relations = relations || []; id = DS.utils.resolveId(definition, id); if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName) + 'id: Must be a string or a number!'); } else if (!DS.utils.isArray(relations)) { throw new IA(errorPrefix(resourceName) + 'relations: Must be an array!'); } var linked = DS.get(resourceName, id); if (linked) { if (!DS.$rootScope.$$phase) { DS.$rootScope.$apply(function () { _link.call(DS, definition, linked, relations); }); } else { _link.call(DS, definition, linked, relations); } } return linked; } module.exports = link; },{}],87:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.linkAll(' + resourceName + '[, params][, relations]): '; } function _linkAll(definition, linked, relations) { var DS = this; DS.utils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DS.utils.contains(relations, relationName)) { return; } if (def.type === 'belongsTo') { DS.utils.forEach(linked, function (injectedItem) { var parent = injectedItem[def.localKey] ? DS.get(relationName, injectedItem[def.localKey]) : null; if (parent) { injectedItem[def.localField] = parent; } }); } else if (def.type === 'hasMany') { DS.utils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; injectedItem[def.localField] = DS.defaults.constructor.prototype.defaultFilter.call(DS, DS.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); }); } else if (def.type === 'hasOne') { DS.utils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; var children = DS.defaults.constructor.prototype.defaultFilter.call(DS, DS.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { injectedItem[def.localField] = children[0]; } }); } }); } /** * @doc method * @id DS.sync methods:linkAll * @name linkAll * @description * Find relations of a collection of items that are already in the data store and link them to the items. * * ## Signature: * ```js * DS.linkAll(resourceName[, params][, relations]) * ``` * * ## Examples: * * Assume `user` has `hasMany` relationships to `post` and `comment`. * ```js * DS.filter('user'); // [{ name: 'John', id: 1 }, { name: 'Sally', id: 2 }] * * // link posts * DS.linkAll('user', { * name: : 'John' * }, ['post']); * * DS.filter('user'); // [{ name: 'John', id: 1, posts: [...] }, { name: 'Sally', id: 2 }] * * // link all relations * DS.linkAll('user', { name: : 'John' }); * * DS.filter('user'); // [{ name: 'John', id: 1, posts: [...], comments: [...] }, { name: 'Sally', id: 2 }] * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object=} params Parameter object that is used to filter items. Properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {array=} relations The relations to be linked. If not provided then all relations will be linked. Default: `[]`. * @returns {object|array} A reference to the item with its linked relations. */ function linkAll(resourceName, params, relations) { var DS = this; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; relations = relations || []; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (params && !DS.utils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } else if (!DS.utils.isArray(relations)) { throw new IA(errorPrefix(resourceName) + 'relations: Must be an array!'); } var linked = DS.filter(resourceName, params); if (linked) { if (!DS.$rootScope.$$phase) { DS.$rootScope.$apply(function () { _linkAll.call(DS, definition, linked, relations); }); } else { _linkAll.call(DS, definition, linked, relations); } } return linked; } module.exports = linkAll; },{}],88:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.linkInverse(' + resourceName + ', id[, relations]): '; } function _linkInverse(definition, relations) { var DS = this; DS.utils.forEach(DS.definitions, function (d) { DS.utils.forEach(d.relations, function (relatedModels) { DS.utils.forEach(relatedModels, function (defs, relationName) { if (relations.length && !DS.utils.contains(relations, d.name)) { return; } if (definition.name === relationName) { DS.linkAll(d.name, {}, [definition.name]); } }); }); }); } /** * @doc method * @id DS.sync methods:linkInverse * @name linkInverse * @description * Find relations of the item with the given primary key that are already in the data store and link this item to those * relations. This creates links in the opposite direction of `DS.link`. * * ## Signature: * ```js * DS.linkInverse(resourceName, id[, relations]) * ``` * * ## Examples: * * Assume `organization` has `hasMany` relationship to `user` and `post` has a `belongsTo` relationship to `user`. * ```js * DS.get('user', 1); // { organizationId: 5, id: 1 } * DS.get('organization', 5); // { id: 5 } * DS.filter('post', { userId: 1 }); // [ { id: 23, userId: 1 }, { id: 44, userId: 1 }] * * // link user to its relations * DS.linkInverse('user', 1, ['organization']); * * DS.get('organization', 5); // { id: 5, users: [{ organizationId: 5, id: 1 }] } * * // link user to all of its all relations * DS.linkInverse('user', 1); * * DS.get('user', 1); // { organizationId: 5, id: 1 } * DS.get('organization', 5); // { id: 5, users: [{ organizationId: 5, id: 1 }] } * DS.filter('post', { userId: 1 }); // [ { id: 23, userId: 1, user: {...} }, { id: 44, userId: 1, user: {...} }] * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item for to link relations. * @param {array=} relations The relations to be linked. If not provided then all relations will be linked. Default: `[]`. * @returns {object|array} A reference to the item with its linked relations. */ function linkInverse(resourceName, id, relations) { var DS = this; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; relations = relations || []; id = DS.utils.resolveId(definition, id); if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName) + 'id: Must be a string or a number!'); } else if (!DS.utils.isArray(relations)) { throw new IA(errorPrefix(resourceName) + 'relations: Must be an array!'); } var linked = DS.get(resourceName, id); if (linked) { if (!DS.$rootScope.$$phase) { DS.$rootScope.$apply(function () { _linkInverse.call(DS, definition, relations); }); } else { _linkInverse.call(DS, definition, relations); } } return linked; } module.exports = linkInverse; },{}],89:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.previous(' + resourceName + '[, ' + id + ']): '; } /** * @doc method * @id DS.sync methods:previous * @name previous * @description * Synchronously return the previous attributes of the item of the type specified by `resourceName` that has the primary key * specified by `id`. This object represents the state of the item the last time it was saved via an async adapter. * * ## Signature: * ```js * DS.previous(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * d; // { author: 'Sally', id: 5 } * * // You may have to do $scope.$apply() first * * DS.previous('document', 5); // { author: 'John Anderson', id: 5 } * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item whose previous attributes are to be retrieved. * @returns {object} The previous attributes of the item of the type specified by `resourceName` with the primary key specified by `id`. */ function previous(resourceName, id) { var DS = this; id = DS.utils.resolveId(DS.definitions[resourceName], id); if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } // return resource from cache return angular.copy(DS.store[resourceName].previousAttributes[id]); } module.exports = previous; },{}],90:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.unlinkInverse(' + resourceName + ', id[, relations]): '; } function _unlinkInverse(definition, linked) { var DS = this; DS.utils.forEach(DS.definitions, function (d) { DS.utils.forEach(d.relations, function (relatedModels) { DS.utils.forEach(relatedModels, function (defs, relationName) { if (definition.name === relationName) { DS.utils.forEach(defs, function (def) { DS.utils.forEach(DS.store[def.name].collection, function (item) { if (def.type === 'hasMany' && item[def.localField]) { var index; DS.utils.forEach(item[def.localField], function (subItem, i) { if (subItem === linked) { index = i; } }); if (index !== undefined) { item[def.localField].splice(index, 1); } } else if (item[def.localField] === linked) { delete item[def.localField]; } }); }); } }); }); }); } /** * @doc method * @id DS.sync methods:unlinkInverse * @name unlinkInverse * @description * Find relations of the item with the given primary key that are already in the data store and _unlink_ this item from those * relations. This unlinks links that would be created by `DS.linkInverse`. * * ## Signature: * ```js * DS.unlinkInverse(resourceName, id[, relations]) * ``` * * ## Examples: * * Assume `organization` has `hasMany` relationship to `user` and `post` has a `belongsTo` relationship to `user`. * ```js * DS.get('organization', 5); // { id: 5, users: [{ organizationId: 5, id: 1 }] } * * // unlink user 1 from its relations * DS.unlinkInverse('user', 1, ['organization']); * * DS.get('organization', 5); // { id: 5, users: [] } * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item for which to unlink relations. * @param {array=} relations The relations to be unlinked. If not provided then all relations will be unlinked. Default: `[]`. * @returns {object|array} A reference to the item that has been unlinked. */ function unlinkInverse(resourceName, id, relations) { var DS = this; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; relations = relations || []; id = DS.utils.resolveId(definition, id); if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName) + 'id: Must be a string or a number!'); } else if (!DS.utils.isArray(relations)) { throw new IA(errorPrefix(resourceName) + 'relations: Must be an array!'); } var linked = DS.get(resourceName, id); if (linked) { if (!DS.$rootScope.$$phase) { DS.$rootScope.$apply(function () { _unlinkInverse.call(DS, definition, linked, relations); }); } else { _unlinkInverse.call(DS, definition, linked, relations); } } return linked; } module.exports = unlinkInverse; },{}],91:[function(require,module,exports){ /** * @doc function * @id errors.types:IllegalArgumentError * @name IllegalArgumentError * @description Error that is thrown/returned when a caller does not honor the pre-conditions of a method/function. * @param {string=} message Error message. Default: `"Illegal Argument!"`. * @returns {IllegalArgumentError} A new instance of `IllegalArgumentError`. */ function IllegalArgumentError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:IllegalArgumentError.type * @name type * @propertyOf errors.types:IllegalArgumentError * @description Name of error type. Default: `"IllegalArgumentError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:IllegalArgumentError.message * @name message * @propertyOf errors.types:IllegalArgumentError * @description Error message. Default: `"Illegal Argument!"`. */ this.message = message || 'Illegal Argument!'; } IllegalArgumentError.prototype = new Error(); IllegalArgumentError.prototype.constructor = IllegalArgumentError; /** * @doc function * @id errors.types:RuntimeError * @name RuntimeError * @description Error that is thrown/returned for invalid state during runtime. * @param {string=} message Error message. Default: `"Runtime Error!"`. * @returns {RuntimeError} A new instance of `RuntimeError`. */ function RuntimeError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:RuntimeError.type * @name type * @propertyOf errors.types:RuntimeError * @description Name of error type. Default: `"RuntimeError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:RuntimeError.message * @name message * @propertyOf errors.types:RuntimeError * @description Error message. Default: `"Runtime Error!"`. */ this.message = message || 'RuntimeError Error!'; } RuntimeError.prototype = new Error(); RuntimeError.prototype.constructor = RuntimeError; /** * @doc function * @id errors.types:NonexistentResourceError * @name NonexistentResourceError * @description Error that is thrown/returned when trying to access a resource that does not exist. * @param {string=} resourceName Name of non-existent resource. * @returns {NonexistentResourceError} A new instance of `NonexistentResourceError`. */ function NonexistentResourceError(resourceName) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:NonexistentResourceError.type * @name type * @propertyOf errors.types:NonexistentResourceError * @description Name of error type. Default: `"NonexistentResourceError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:NonexistentResourceError.message * @name message * @propertyOf errors.types:NonexistentResourceError * @description Error message. Default: `"Runtime Error!"`. */ this.message = (resourceName || '') + ' is not a registered resource!'; } NonexistentResourceError.prototype = new Error(); NonexistentResourceError.prototype.constructor = NonexistentResourceError; /** * @doc interface * @id errors * @name angular-data error types * @description * Various error types that may be thrown by angular-data. * * - [IllegalArgumentError](/documentation/api/api/errors.types:IllegalArgumentError) * - [RuntimeError](/documentation/api/api/errors.types:RuntimeError) * - [NonexistentResourceError](/documentation/api/api/errors.types:NonexistentResourceError) * * References to the constructor functions of these errors can be found in `DS.errors`. */ module.exports = [function () { return { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; }]; },{}],92:[function(require,module,exports){ (function (window, angular, undefined) { 'use strict'; /** * @doc overview * @id angular-data * @name angular-data * @description * ## Install * * #### Bower * ```text * bower install angular-data * ``` * * Load `dist/angular-data.js` or `dist/angular-data.min.js` onto your web page after Angular.js. * * #### Npm * ```text * npm install angular-data * ``` * * Load `dist/angular-data.js` or `dist/angular-data.min.js` onto your web page after Angular.js. * * #### Manual download * Download angular-data from the [Releases](https://github.com/jmdobry/angular-data/releases) * section of the angular-data GitHub project. * * ## Load into Angular * Your Angular app must depend on the module `"angular-data.DS"` in order to use angular-data. Loading * angular-data into your app allows you to inject the following: * * - `DS` * - `DSHttpAdapter` * - `DSUtils` * - `DSErrors` * * [DS](/documentation/api/api/DS) is the Data Store itself, which you will inject often. * [DSHttpAdapter](/documentation/api/api/DSHttpAdapter) is useful as a wrapper for `$http` and is configurable. * [DSUtils](/documentation/api/api/DSUtils) has some useful utility methods. * [DSErrors](/documentation/api/api/DSErrors) provides references to the various errors thrown by the data store. */ angular.module('angular-data.DS', ['ng']) .factory('DSUtils', require('./utils')) .factory('DSErrors', require('./errors')) .provider('DSHttpAdapter', require('./adapters/http')) .provider('DSLocalStorageAdapter', require('./adapters/localStorage')) .provider('DS', require('./datastore')) .config(['$provide', function ($provide) { $provide.decorator('$q', ['$delegate', function ($delegate) { // do whatever you you want $delegate.promisify = function (fn, target) { if (!fn) { return; } else if (typeof fn !== 'function') { throw new Error('Can only promisify functions!'); } var $q = this; return function () { var deferred = $q.defer(); var args = Array.prototype.slice.apply(arguments); args.push(function (err, result) { if (err) { deferred.reject(err); } else { deferred.resolve(result); } }); try { var promise = fn.apply(target || this, args); if (promise && promise.then) { promise.then(deferred.resolve, deferred.reject); } } catch (err) { deferred.reject(err); } return deferred.promise; }; }; return $delegate; }]); }]); })(window, window.angular); },{"./adapters/http":54,"./adapters/localStorage":55,"./datastore":67,"./errors":91,"./utils":93}],93:[function(require,module,exports){ var DSErrors = require('./errors'); function Events(target) { var events = {}; target = target || this; /** * On: listen to events */ target.on = function (type, func, ctx) { events[type] = events[type] || []; events[type].push({ f: func, c: ctx }); }; /** * Off: stop listening to event / specific callback */ target.off = function (type, func) { var listeners = events[type]; if (!listeners) { events = {}; } else if (func) { for (var i = 0; i < listeners.length; i++) { if (listeners[i] === func) { listeners.splice(i, 1); break; } } } else { listeners.splice(0, listeners.length); } }; target.emit = function () { var args = Array.prototype.slice.call(arguments); var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } var toPromisify = [ 'beforeValidate', 'validate', 'afterValidate', 'beforeCreate', 'afterCreate', 'beforeUpdate', 'afterUpdate', 'beforeDestroy', 'afterDestroy' ]; var find = require('mout/array/find'); var isRegExp = require('mout/lang/isRegExp'); var deepEquals = angular.equals; function isBlacklisted(prop, blacklist) { if (!blacklist || !blacklist.length) { return false; } var matches = find(blacklist, function (blItem) { if ((isRegExp(blItem) && blItem.test(prop)) || blItem === prop) { return prop; } }); return !!matches; } module.exports = ['$q', function ($q) { return { isBoolean: require('mout/lang/isBoolean'), isString: angular.isString, isArray: angular.isArray, isObject: angular.isObject, isNumber: angular.isNumber, isFunction: angular.isFunction, isEmpty: require('mout/lang/isEmpty'), isRegExp: isRegExp, toJson: JSON.stringify, fromJson: angular.fromJson, makePath: require('mout/string/makePath'), upperCase: require('mout/string/upperCase'), pascalCase: require('mout/string/pascalCase'), deepMixIn: require('mout/object/deepMixIn'), deepEquals: deepEquals, mixIn: require('mout/object/mixIn'), forEach: angular.forEach, pick: require('mout/object/pick'), set: require('mout/object/set'), merge: require('mout/object/merge'), contains: require('mout/array/contains'), filter: require('mout/array/filter'), find: find, toLookup: require('mout/array/toLookup'), remove: require('mout/array/remove'), slice: require('mout/array/slice'), sort: require('mout/array/sort'), guid: require('mout/random/guid'), copy: angular.copy, keys: require('mout/object/keys'), _: function (parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!_this.isObject(options)) { throw new DSErrors.IA('"options" must be an object!'); } _this.forEach(toPromisify, function (name) { if (typeof options[name] === 'function') { options[name] = $q.promisify(options[name]); } }); var O = function Options(attrs) { _this.mixIn(this, attrs); }; O.prototype = parent; return new O(options); }, resolveItem: function (resource, idOrInstance) { if (resource && (this.isString(idOrInstance) || this.isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } }, resolveId: function (definition, idOrInstance) { if (this.isString(idOrInstance) || this.isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } }, updateTimestamp: function (timestamp) { var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } }, deepFreeze: function deepFreeze(o) { if (typeof Object.freeze === 'function') { var prop, propKey; Object.freeze(o); // First freeze the object. for (propKey in o) { prop = o[propKey]; if (!o.hasOwnProperty(propKey) || typeof prop !== 'object' || Object.isFrozen(prop)) { // If the object is on the prototype, not an object, or is already frozen, // skip it. Note that this might leave an unfrozen reference somewhere in the // object if there is an already frozen object containing an unfrozen object. continue; } deepFreeze(prop); // Recursively call deepFreeze. } } }, diffObjectFromOldObject: function (object, oldObject, blacklist) { var added = {}; var removed = {}; var changed = {}; blacklist = blacklist || []; for (var prop in oldObject) { var newValue = object[prop]; if (isBlacklisted(prop, blacklist)) { continue; } if (newValue !== undefined && deepEquals(newValue, oldObject[prop])) { continue; } if (!(prop in object)) { removed[prop] = undefined; continue; } if (!deepEquals(newValue, oldObject[prop])) { changed[prop] = newValue; } } for (var prop2 in object) { if (prop2 in oldObject) { continue; } if (isBlacklisted(prop2, blacklist)) { continue; } added[prop2] = object[prop2]; } return { added: added, removed: removed, changed: changed }; }, Events: Events }; }]; },{"./errors":91,"mout/array/contains":2,"mout/array/filter":3,"mout/array/find":4,"mout/array/remove":9,"mout/array/slice":10,"mout/array/sort":11,"mout/array/toLookup":12,"mout/lang/isBoolean":19,"mout/lang/isEmpty":20,"mout/lang/isRegExp":25,"mout/object/deepMixIn":31,"mout/object/keys":35,"mout/object/merge":36,"mout/object/mixIn":37,"mout/object/pick":39,"mout/object/set":40,"mout/random/guid":42,"mout/string/makePath":49,"mout/string/pascalCase":50,"mout/string/upperCase":53}]},{},[92]);
RN HotUpdate/SmartHomeII/main.js
HarrisLee/React-Native-Express
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, ListView, Image, Platform, Navigator, TouchableHighlight, TouchableOpacity } from 'react-native'; import Constanst from './SmartHome/Global/Constant.js'; import MainPage from './indexPage.js'; export default class CollectionView extends Component { constructor(props) { super(props); this.state = { }; } render() { console.log(this.props.appName); console.log('screen width ' + Constanst.navigtor_height); console.log('screen width ' + Constanst.nameExport); return ( <Navigator initialRoute={{name:'首页', index: 0, component:MainPage, showNaviBar:true}} ref='navigator' renderScene={(route, navigator) => <route.component style={{flex:1}} {...route.params} route={route} navigator={navigator} name={route.name}/>} > </Navigator> ); } } /* //navigator的一个配置项 navigationBar={<Navigator.NavigationBar style={styles.navContainer} routeMapper={NavigationBarRouteMapper}/>} // 导航栏的Mapper var NavigationBarRouteMapper = { // 左键 LeftButton(route, navigator, index, navState) { if (global.CONSTANST.showNaviBar == false) { return null; } if (index > 0) { return ( <View style={styles.navContainer}> <TouchableOpacity underlayColor='transparent' onPress={() => {if (index > 0) {navigator.pop()}}}> <Text style={styles.leftNavButtonText}> 后退 </Text> </TouchableOpacity> </View> ); } else { return null; } }, // 右键 RightButton(route, navigator, index, navState) { if (global.CONSTANST.showNaviBar == false) { return null; } if (route.onPress) return ( <View style={styles.navContainer}> <TouchableOpacity onPress={() => route.onPress()}> <Text style={styles.rightNavButtonText}> {route.rightText || '右键'} </Text> </TouchableOpacity> </View> ); }, // 标题 Title(route, navigator, index, navState) { if (global.CONSTANST.showNaviBar == false) { return null; } return ( <View style={styles.navContainer}> <Text style={styles.title}> {route.title} </Text> </View> ); } }; //导航栏按钮的样式 const styles = StyleSheet.create({ navContainer: { backgroundColor: '#81c04d', paddingTop: 12, paddingBottom: 10, height : 0, } }); */
client/app/components/contact.js
poddarh/nectarine
import {sendContactEmail} from '../server.js'; import React from 'react'; export default class Contact extends React.Component { constructor(props) { super(props); this.state = { //input fields name: "", email: "", typeOfIssue: "", question: "", data: [], message: "" } } handleSubmit(e){ e.preventDefault(); var thisName = this.state.name.trim(); var thisEmail = this.state.email.trim(); var thisTOI = this.state.typeOfIssue.trim(); var thisQuestion = this.state.question.trim(); if (thisName == "") { this.setState({message: "You need to enter a name"}); } else if (thisEmail == "") { this.setState({message: "You need to enter an email"}); } else if (thisTOI == "") { this.setState({message: "You need to enter a type of issue"}); } else if (thisQuestion == "") { this.setState({message: "You need to enter a question"}); } else if (thisName !== "" && thisEmail !== "" && thisTOI !== "" && thisQuestion !== "") { var newData = { name: thisName, email: thisEmail, typeOfIssue: thisTOI, question: thisQuestion } sendContactEmail(newData, (data) => { if (data.success == true) { this.setState({name: "", email: "", typeOfIssue: "", question: "", data: [], message: "Your form has been submitted!"}) } else{ this.setState({message: "Unexpected error occurred!"}) } }); } } handleChange(key, e) { e.preventDefault(); var state = {} state[key] = e.target.value; this.setState(state); } render() { return ( <div className="row"> <div className="col-md-6"> <div className="row"> <div className="col-md-10"> <div className="form-group"> Full Name <input type="text" className="form-control" placeholder={this.state.data.name} value={this.state.name} onChange={(e) => this.handleChange("name", e)}/> </div> </div> </div> <div className="row"> <div className="col-md-10"> <div className="form-group"> Email <input type="text" className="form-control" placeholder={this.state.data.email} value={this.state.email} onChange={(e) => this.handleChange("email", e)}/> </div> </div> </div> <div className="row"> <div className="col-md-10"> <div className="form-group"> Type of Issue <input type="text" className="form-control" placeholder={this.state.data.typeOfIssue} value={this.state.typeOfIssue} onChange={(e) => this.handleChange("typeOfIssue", e)}/> </div> </div> </div> <div className="row"> <div className="col-md-10"> <div className="form-group"> Question <textarea className="form-control" rows="5" placeholder={this.state.data.question} value={this.state.question} onChange={(e) => this.handleChange("question", e)}/> </div> </div> </div> <button type="submit" className="btn btn-primary" onClick={(e) => this.handleSubmit(e)}>Submit</button> <p></p>{this.state.message} <div id="db-reset"></div> </div> </div> ) } }
ajax/libs/rx-player/1.4.1/rx-player.js
extend1994/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["RxPlayer"] = factory(); else root["RxPlayer"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; module.exports = __webpack_require__(32); /***/ }, /* 1 */ /***/ function(module, exports) { "use strict"; var objectProto = Object.prototype; var toString = objectProto.toString; var ownProperty = objectProto.hasOwnProperty; var isArray = Array.isArray; var push = Array.prototype.push; var keys = Object.keys || function (obj) { var k = []; for (var attr in obj) { if (obj.hasOwnProperty(attr)) { k.push(obj[attr]); } } return k; }; function indexOf(arr, value) { var i = -1; var l = arr ? arr.length : 0; while (++i < l) { if (arr[i] === value) return i; } return -1; } function groupBy(arr, prop) { var fn; if (isFunction(prop)) fn = prop;else fn = function (v) { return v[prop]; }; return reduce(arr, function (result, val) { var key = fn(val); (isArray(result[key]) ? result[key] : result[key] = []).push(val); return result; }, {}); } function sortedIndex(arr, value, fn) { var low = 0; var high = arr ? arr.length : low; value = fn(value); while (low < high) { var mid = low + high >>> 1; if (fn(arr[mid]) < value) { low = mid + 1; } else { high = mid; } } return low; } function sortedMerge(arr1, arr2, sortValue) { var i = 0, j = 0, k = 0, p; var m = arr1.length, n = arr2.length; var arr = []; while (i < m && j < n) { if (arr1[i][sortValue] <= arr2[j][sortValue]) { arr[k] = arr1[i];i++;k++; } else if (k > 0 && arr2[j][sortValue] <= arr[k - 1][sortValue]) { j++; } else { arr[k] = arr2[j];j++;k++; } } if (i < m) { for (p = i; p < m; p++) { arr[k] = arr1[p];k++; } } else { for (p = j; p < n; p++) { arr[k] = arr2[p];k++; } } return arr; } function find(arr, fn) { var i = -1; var l = arr ? arr.length : 0; while (++i < l) { if (fn(arr[i], i)) return arr[i]; } } function between(arr, f, v) { var i = -1; var l = arr ? arr.length : 0; while (++i < l) { if (arr[i][f] <= v && arr[i + 1] && v < arr[i + 1][f]) return arr[i]; } } function findLast(arr, fn) { var i = arr ? arr.length : 0; while (--i >= 0) { if (fn(arr[i], i)) return arr[i]; } } function baseFlatten(arr, fromIndex) { var i = (fromIndex || 0) - 1; var l = arr ? arr.length : 0; var n = []; while (++i < l) { var value = arr[i]; if (value && typeof value == "object" && typeof value.length == "number") { var valIndex = -1; var valLength = value.length; var resIndex = n.length; n.length += valLength; while (++valIndex < valLength) { n[resIndex++] = value[valIndex]; } } else { n.push(value); } } return n; } function flatten(arr, fn) { return baseFlatten(fn ? map(arr, fn) : arr, 0); } function isDate(value) { return !!value && typeof value == "object" && toString.call(value) == "[object Date]" || false; } function isFunction(value) { return !!value && typeof value == "function" || false; } function isNumber(value) { return typeof value == "number"; } function isObject(value) { return !!value && typeof value == "object" || false; } function isString(value) { return typeof value == "string"; } function isPromise(value) { return !!value && typeof value.then == "function"; } function isObservable(value) { return !!value && typeof value.subscribe == "function"; } function identity(x) { return x; } function noop() { return; } function last(arr) { return arr[arr.length - 1]; } var uniqueId = (function () { var __id = 0; return function (prefix) { if (!prefix) prefix = ""; return "" + prefix + __id++; }; })(); function contains(arr, value) { return indexOf(arr, value) > -1; } function extend(dst) { var args = arguments; for (var i = 1; i < args.length; i++) { var src = args[i]; if (!isObject(src)) continue; var ks = keys(src); for (var j = 0, l = ks.length; j < l; j++) { dst[ks[j]] = src[ks[j]]; } } return dst; } function defaults(obj, def) { for (var attr in def) { if (typeof obj[attr] == "undefined") { obj[attr] = def[attr]; } } return obj; } function cloneObject(obj) { return extend({}, obj); } function cloneArray(arr) { var l = arr ? arr.length : 0; var i = -1; var n = Array(l); while (++i < l) n[i] = arr[i]; return n; } function map(arr, fn) { var l = arr ? arr.length : 0; var i = -1; var n = Array(l); while (++i < l) n[i] = fn(arr[i], i); return n; } function reduce(arr, fn, init) { var l = arr ? arr.length : 0; var i = -1; var n = init; while (++i < l) n = fn(n, arr[i], i); return n; } function each(arr, fn) { var l = arr ? arr.length : 0; var i = -1; while (++i < l) fn(arr[i], i); } function values(object) { var props = keys(object); var i = -1; var l = props.length; var n = Array(l); while (++i < l) n[i] = object[props[i]]; return n; } function filter(arr, fn) { var l = arr ? arr.length : 0; var i = -1; var n = []; while (++i < l) { if (fn(arr[i], i)) n.push(arr[i]); } return n; } function compact(arr) { return filter(arr, function (i) { return i != null; }); } function memoize(fn, resolver) { var memoized = function memoized() { var cache = memoized.cache; var key = resolver ? resolver.apply(this, arguments) : arguments[0]; return ownProperty.call(cache, key) ? cache[key] : cache[key] = fn.apply(this, arguments); }; memoized.cache = {}; return memoized; } function pick(object, vals) { return reduce(vals, function (result, key) { if (key in object) result[key] = object[key]; return result; }, {}); } function pluck(arr, key) { return map(arr, function (o) { return o[key]; }); } function tryCatch(fn) { try { return fn(); } catch (e) { return e; } } function simpleMerge(source, dist) { for (var attr in source) { if (!dist.hasOwnProperty(attr)) continue; var src = source[attr]; var dst = dist[attr]; if (isString(src) || isNumber(src) || isDate(src)) { source[attr] = dst; } else if (isArray(src)) { src.length = 0; push.apply(src, dst); } else { source[attr] = simpleMerge(src, dst); } } return source; } function chunk(arr, size) { var r = []; var c = 0; var i = -1; var l = arr ? arr.length : 0; while (++i < l) { if (!r[c]) { r[c] = [arr[i]]; } else { if (r[c].length === size) { r[++c] = [arr[i]]; } else { r[c].push(arr[i]); } } } return r; } function pad(n, l) { n = n.toString(); if (n.length >= l) { return n; } var arr = new Array(l + 1).join("0") + n; return arr.slice(-l); } module.exports = { chunk: chunk, compact: compact, contains: contains, cloneArray: cloneArray, cloneObject: cloneObject, defaults: defaults, each: each, extend: extend, values: values, filter: filter, find: find, between: between, findLast: findLast, flatten: flatten, groupBy: groupBy, identity: identity, indexOf: indexOf, isArray: isArray, isDate: isDate, isFunction: isFunction, isNumber: isNumber, isObject: isObject, isString: isString, isPromise: isPromise, isObservable: isObservable, keys: keys, last: last, map: map, memoize: memoize, noop: noop, pad: pad, pick: pick, pluck: pluck, reduce: reduce, simpleMerge: simpleMerge, sortedIndex: sortedIndex, sortedMerge: sortedMerge, tryCatch: tryCatch, uniqueId: uniqueId }; /***/ }, /* 2 */ /***/ function(module, exports) { "use strict"; function AssertionError(message) { this.name = "AssertionError"; this.message = message; if (Error.captureStackTrace) { Error.captureStackTrace(this, AssertionError); } } AssertionError.prototype = new Error(); function assert(value, message) { if (!value) throw new AssertionError(message); } assert.equal = function (a, b, message) { return assert(a === b, message); }; assert.iface = function (o, name, iface) { assert(o, name + " should be an object"); for (var k in iface) assert.equal(typeof o[k], iface[k], name + " should have property " + k + " as a " + iface[k]); }; module.exports = assert; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { "use strict"; __webpack_require__(5); module.exports = __webpack_require__(13); /***/ }, /* 4 */ /***/ function(module, exports) { "use strict"; var Levels = { NONE: 0, ERROR: 1, WARNING: 2, INFO: 3, DEBUG: 4 }; var noop = function noop() {}; function log() {} log.error = noop; log.warn = noop; log.info = noop; log.debug = noop; log.setLevel = function (level) { if (typeof level == "string") { level = Levels[level]; } log.error = level >= Levels.ERROR ? console.error.bind(console) : noop; log.warn = level >= Levels.WARNING ? console.warn.bind(console) : noop; log.info = level >= Levels.INFO ? console.info.bind(console) : noop; log.debug = level >= Levels.DEBUG ? console.log.bind(console) : noop; }; module.exports = log; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _require = __webpack_require__(13); var Observable = _require.Observable; var SingleAssignmentDisposable = _require.SingleAssignmentDisposable; var config = _require.config; var fromEvent = Observable.fromEvent; var merge = Observable.merge; var timer = Observable.timer; var _require2 = __webpack_require__(20); var getBackedoffDelay = _require2.getBackedoffDelay; var _require3 = __webpack_require__(1); var identity = _require3.identity; var isArray = _require3.isArray; var map = _require3.map; var noop = _require3.noop; var debounce = __webpack_require__(21); config.useNativeEvents = true; var observableProto = Observable.prototype; if (false) { observableProto.log = function (ns, fn) { if (!ns) ns = ""; return this["do"](function (x) { return console.log(ns, "next", (fn || identity)(x)); }, function (e) { return console.log(ns, "error", e); }, function () { return console.log(ns, "completed"); }); }; } else { observableProto.log = function () { return this; }; } observableProto.each = function (onNext) { return this.subscribe(onNext, noop); }; var simpleEquals = function simpleEquals(a, b) { return a === b; }; observableProto.changes = function (keySelector) { return this.distinctUntilChanged(keySelector, simpleEquals); }; observableProto.customDebounce = function (time, debounceOptions) { var source = this; return Observable.create(function (observer) { var debounced = debounce(function (val) { return observer.onNext(val); }, time, debounceOptions); var subscribe = source.subscribe(debounced, function (e) { return observer.onError(e); }, function () { return observer.onCompleted(); }); return function () { debounced.dispose(); subscribe.dispose(); }; }); }; observableProto.simpleTimeout = function (time) { var errMessage = arguments.length <= 1 || arguments[1] === undefined ? "timeout" : arguments[1]; var source = this; return Observable.create(function (observer) { var sad = new SingleAssignmentDisposable(); var timer = setTimeout(function () { return observer.onError(new Error(errMessage)); }, time); sad.setDisposable(source.subscribe(function (x) { clearTimeout(timer); observer.onNext(x); }, function (e) { return observer.onError(e); }, function (_) { return observer.onCompleted(); })); return function () { clearTimeout(timer); sad.dispose(); }; }); }; function retryWithBackoff(fn, _ref) { var retryDelay = _ref.retryDelay; var totalRetry = _ref.totalRetry; var shouldRetry = _ref.shouldRetry; var resetDelay = _ref.resetDelay; var retryCount = 0; var debounceRetryCount; if (resetDelay > 0) { debounceRetryCount = debounce(function () { return retryCount = 0; }, resetDelay); } else { debounceRetryCount = noop; } return function doRetry() { // do not leak arguments for (var i = 0, l = arguments.length, args = Array(l); i < l; i++) args[i] = arguments[i]; return fn.apply(null, args)["catch"](function (err) { var wantRetry = !shouldRetry || shouldRetry(err, retryCount); if (!wantRetry || retryCount++ >= totalRetry) { throw err; } var fuzzedDelay = getBackedoffDelay(retryDelay, retryCount); return timer(fuzzedDelay).flatMap(function () { debounceRetryCount(); return doRetry.apply(null, args); }); }); }; } module.exports = { on: function on(elt, evts) { if (isArray(evts)) { return merge(map(evts, function (evt) { return fromEvent(elt, evt); })); } else { return fromEvent(elt, evts); } }, first: function first(obs) { return obs.take(1); }, only: function only(x) { return Observable.never().startWith(x); }, retryWithBackoff: retryWithBackoff }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__(48).Promise; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var assert = __webpack_require__(2); function totalBytes(arr) { var tot = 0; for (var i = 0; i < arr.length; i++) { tot += arr[i].byteLength; } return tot; } function strToBytes(str) { var len = str.length; var arr = new Uint8Array(len); for (var i = 0; i < len; i++) { arr[i] = str.charCodeAt(i) & 0xFF; } return arr; } function bytesToStr(bytes) { return String.fromCharCode.apply(null, bytes); } function bytesToUTF16Str(bytes) { var str = ""; var len = bytes.length; for (var i = 0; i < len; i += 2) str += String.fromCharCode(bytes[i]); return str; } function hexToBytes(str) { var len = str.length; var arr = new Uint8Array(len / 2); for (var i = 0, j = 0; i < len; i += 2, j++) { arr[j] = parseInt(str.substr(i, 2), 16) & 0xFF; } return arr; } function bytesToHex(bytes, sep) { if (!sep) sep = ""; var hex = ""; for (var i = 0; i < bytes.byteLength; i++) { hex += (bytes[i] >>> 4).toString(16); hex += (bytes[i] & 0xF).toString(16); if (sep.length) hex += sep; } return hex; } function concat() { var l = arguments.length, i = -1; var len = 0, arg; while (++i < l) { arg = arguments[i]; len += typeof arg === "number" ? arg : arg.length; } var arr = new Uint8Array(len); var off = 0; i = -1; while (++i < l) { arg = arguments[i]; if (typeof arg === "number") { off += arg; } else if (arg.length > 0) { arr.set(arg, off); off += arg.length; } } return arr; } function be2toi(bytes, off) { return (bytes[0 + off] << 8) + (bytes[1 + off] << 0); } function be4toi(bytes, off) { return bytes[0 + off] * 0x1000000 + bytes[1 + off] * 0x0010000 + bytes[2 + off] * 0x0000100 + bytes[3 + off]; } function be8toi(bytes, off) { return (bytes[0 + off] * 0x1000000 + bytes[1 + off] * 0x0010000 + bytes[2 + off] * 0x0000100 + bytes[3 + off]) * 0x100000000 + bytes[4 + off] * 0x1000000 + bytes[5 + off] * 0x0010000 + bytes[6 + off] * 0x0000100 + bytes[7 + off]; } function itobe2(num) { return new Uint8Array([num >>> 8 & 0xFF, num & 0xFF]); } function itobe4(num) { return new Uint8Array([num >>> 24 & 0xFF, num >>> 16 & 0xFF, num >>> 8 & 0xFF, num & 0xFF]); } function itobe8(num) { var l = num % 0x100000000; var h = (num - l) / 0x100000000; return new Uint8Array([h >>> 24 & 0xFF, h >>> 16 & 0xFF, h >>> 8 & 0xFF, h & 0xFF, l >>> 24 & 0xFF, l >>> 16 & 0xFF, l >>> 8 & 0xFF, l & 0xFF]); } function le2toi(bytes, off) { return (bytes[0 + off] << 0) + (bytes[1 + off] << 8); } function le4toi(bytes, off) { return bytes[0 + off] + bytes[1 + off] * 0x0000100 + bytes[2 + off] * 0x0010000 + bytes[3 + off] * 0x1000000; } function le8toi(bytes, off) { return bytes[0 + off] + bytes[1 + off] * 0x0000100 + bytes[2 + off] * 0x0010000 + bytes[3 + off] * 0x1000000 + (bytes[4 + off] + bytes[5 + off] * 0x0000100 + bytes[6 + off] * 0x0010000 + bytes[7 + off] * 0x1000000 * 0x100000000); } function itole2(num) { return new Uint8Array([num & 0xFF, num >>> 8 & 0xFF]); } function itole4(num) { return new Uint8Array([num & 0xFF, num >>> 8 & 0xFF, num >>> 16 & 0xFF, num >>> 24 & 0xFF]); } function itole8(num) { var l = num % 0x100000000; var h = (num - l) / 0x100000000; return new Uint8Array([h & 0xFF, h >>> 8 & 0xFF, h >>> 16 & 0xFF, h >>> 24 & 0xFF, l & 0xFF, l >>> 8 & 0xFF, l >>> 16 & 0xFF, l >>> 24 & 0xFF]); } function guidToUuid(uuid) { assert.equal(uuid.length, 16, "UUID length should be 16"); var buf = strToBytes(uuid); var p1A = buf[0]; var p1B = buf[1]; var p1C = buf[2]; var p1D = buf[3]; var p2A = buf[4]; var p2B = buf[5]; var p3A = buf[6]; var p3B = buf[7]; var p4 = buf.subarray(8, 10); var p5 = buf.subarray(10, 16); var ord = new Uint8Array(16); ord[0] = p1D;ord[1] = p1C;ord[2] = p1B;ord[3] = p1A; // swap32 BE -> LE ord[4] = p2B;ord[5] = p2A; // swap16 BE -> LE ord[6] = p3B;ord[7] = p3A; // swap16 BE -> LE ord.set(p4, 8); ord.set(p5, 10); return bytesToHex(ord); } function toBase64URL(str) { return btoa(str).replace(/\=+$/, ""); } module.exports = { totalBytes: totalBytes, strToBytes: strToBytes, bytesToStr: bytesToStr, bytesToUTF16Str: bytesToUTF16Str, hexToBytes: hexToBytes, bytesToHex: bytesToHex, concat: concat, be2toi: be2toi, be4toi: be4toi, be8toi: be8toi, le2toi: le2toi, le4toi: le4toi, le8toi: le8toi, itobe2: itobe2, itobe4: itobe4, itobe8: itobe8, itole2: itole2, itole4: itole4, itole8: itole8, guidToUuid: guidToUuid, toBase64URL: toBase64URL }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _ = __webpack_require__(1); var log = __webpack_require__(4); var Promise_ = __webpack_require__(6); var EventEmitter = __webpack_require__(10); var _require = __webpack_require__(7); var bytesToStr = _require.bytesToStr; var strToBytes = _require.strToBytes; var assert = __webpack_require__(2); var _require2 = __webpack_require__(3); var Observable = _require2.Observable; var merge = Observable.merge; var never = Observable.never; var fromEvent = Observable.fromEvent; var just = Observable.just; var _require3 = __webpack_require__(5); var on = _require3.on; var doc = document; var win = window; var PREFIXES = ["", "webkit", "moz", "ms"]; var HTMLElement_ = win.HTMLElement; var HTMLVideoElement_ = win.HTMLVideoElement; var MediaSource_ = win.MediaSource || win.MozMediaSource || win.WebKitMediaSource || win.MSMediaSource; var MediaKeys_ = win.MediaKeys || win.MozMediaKeys || win.WebKitMediaKeys || win.MSMediaKeys; var isIE = navigator.appName == "Microsoft Internet Explorer" || navigator.appName == "Netscape" && /Trident\//.test(navigator.userAgent); var MockMediaKeys = _.noop; var requestMediaKeySystemAccess; if (navigator.requestMediaKeySystemAccess) requestMediaKeySystemAccess = function (a, b) { return navigator.requestMediaKeySystemAccess(a, b); }; // @implement interface MediaKeySystemAccess var KeySystemAccess = (function () { function KeySystemAccess(keyType, mediaKeys, mediaKeySystemConfiguration) { _classCallCheck(this, KeySystemAccess); this._keyType = keyType; this._mediaKeys = mediaKeys; this._configuration = mediaKeySystemConfiguration; } KeySystemAccess.prototype.createMediaKeys = function createMediaKeys() { return Promise_.resolve(this._mediaKeys); }; KeySystemAccess.prototype.getConfiguration = function getConfiguration() { return this._configuration; }; _createClass(KeySystemAccess, [{ key: "keySystem", get: function get() { return this._keyType; } }]); return KeySystemAccess; })(); function castToPromise(prom) { if (prom && typeof prom.then == "function") { return prom; } else { return Promise_.resolve(prom); } } function wrap(fn) { return function () { var retValue; try { retValue = fn.apply(this, arguments); } catch (error) { return Promise_.reject(error); } return castToPromise(retValue); }; } function isEventSupported(element, eventNameSuffix) { var clone = document.createElement(element.tagName); var eventName = "on" + eventNameSuffix; if (eventName in clone) { return true; } else { clone.setAttribute(eventName, "return;"); return _.isFunction(clone[eventName]); } } function eventPrefixed(eventNames, prefixes) { return _.flatten(eventNames, function (name) { return _.map(prefixes || PREFIXES, function (p) { return p + name; }); }); } function findSupportedEvent(element, eventNames) { return _.find(eventNames, function (name) { return isEventSupported(element, name); }); } function compatibleListener(eventNames, prefixes) { var mem; eventNames = eventPrefixed(eventNames, prefixes); return function (element) { // if the element is a HTMLElement we can detect // the supported event, and memoize it in `mem` if (element instanceof HTMLElement_) { if (typeof mem == "undefined") { mem = findSupportedEvent(element, eventNames) || null; } if (mem) { return fromEvent(element, mem); } else { if (false) { log.warn("compat: element <" + element.tagName + "> does not support any of these events: " + eventNames.join(", ")); } return never(); } } // otherwise, we need to listen to all the events // and merge them into one observable sequence return on(element, eventNames); }; } function isCodecSupported(codec) { return !!MediaSource_ && MediaSource_.isTypeSupported(codec); } // On IE11, we use the "progress" instead of "loadedmetadata" to set // the "currentTime. // // Internet Explorer emits an error when setting the "currentTime" // before a "progress" event sent just after the "loadedmetadata" // after receiving the first init-segments. Other browsers do not // even send this "progress" before receiving the first data-segment. // // TODO(pierre): try to find a solution without "browser sniffing"... var loadedMetadataEvent = compatibleListener(isIE ? ["progress"] : ["loadedmetadata"]); var sourceOpenEvent = compatibleListener(["sourceopen", "webkitsourceopen"]); var onEncrypted = compatibleListener(["encrypted", "needkey"]); var onKeyMessage = compatibleListener(["keymessage", "message"]); var onKeyAdded = compatibleListener(["keyadded", "ready"]); var onKeyError = compatibleListener(["keyerror", "error"]); var onKeyStatusesChange = compatibleListener(["keystatuseschange"]); var emeEvents = { onEncrypted: onEncrypted, onKeyMessage: onKeyMessage, onKeyStatusesChange: onKeyStatusesChange, onKeyError: onKeyError }; function sourceOpen(mediaSource) { if (mediaSource.readyState == "open") return just();else return sourceOpenEvent(mediaSource).take(1); } function loadedMetadata(videoElement) { if (videoElement.readyState >= HTMLVideoElement.HAVE_METADATA) return just();else return loadedMetadataEvent(videoElement).take(1); } function canPlay(videoElement) { if (videoElement.readyState >= HTMLVideoElement.HAVE_ENOUGH_DATA) return just();else return on(videoElement, "canplay").take(1); } // Wrap "MediaKeys.prototype.update" form an event based system to a // Promise based function. function wrapUpdateWithPromise(memUpdate, sessionObj) { function KeySessionError() { var err = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (err.errorCode) { err = { systemCode: err.systemCode, code: err.errorCode.code }; } this.name = "KeySessionError"; this.mediaKeyError = err; this.message = "MediaKeyError code:" + err.code + " and systemCode:" + err.systemCode; } KeySessionError.prototype = new Error(); return function (license, sessionId) { var session = _.isFunction(sessionObj) ? sessionObj.call(this) : this; var keys = onKeyAdded(session); var errs = onKeyError(session).map(function (evt) { throw new KeySessionError(session.error || evt); }); try { memUpdate.call(this, license, sessionId); return merge(keys, errs).take(1).toPromise(); } catch (e) { return Promise_.reject(e); } }; } // Browser without any MediaKeys object: A mock for MediaKey and // MediaKeySession are created, and the <video>.addKey api is used to // pass the license. // This is for Chrome with unprefixed EME api if (!requestMediaKeySystemAccess && HTMLVideoElement_.prototype.webkitGenerateKeyRequest) { // Mock MediaKeySession interface for old chrome implementation // of the EME specifications var MockMediaKeySession = function MockMediaKeySession(video, keySystem) { var _this = this; EventEmitter.call(this); this._vid = video; this._key = keySystem; this._con = merge(onKeyMessage(video), onKeyAdded(video), onKeyError(video)).subscribe(function (evt) { return _this.trigger(evt.type, evt); }); }; MockMediaKeySession.prototype = _.extend({}, EventEmitter.prototype, { generateRequest: wrap(function (initDataType, initData) { this._vid.webkitGenerateKeyRequest(this._key, initData); }), update: wrapUpdateWithPromise(function (license, sessionId) { if (this._key.indexOf("clearkey") >= 0) { var json = JSON.parse(bytesToStr(license)); var key = strToBytes(atob(json.keys[0].k)); var kid = strToBytes(atob(json.keys[0].kid)); this._vid.webkitAddKey(this._key, key, kid, sessionId); } else { this._vid.webkitAddKey(this._key, license, null, sessionId); } }), close: wrap(function () { if (this._con) this._con.dispose(); this._con = null; this._vid = null; }) }); MockMediaKeys = function (keySystem) { this.ks_ = keySystem; }; MockMediaKeys.prototype = { _setVideo: function _setVideo(vid) { this._vid = vid; }, createSession: function createSession() /* sessionType */{ return new MockMediaKeySession(this._vid, this.ks_); } }; var isTypeSupported = function isTypeSupported(keyType) { // get any <video> element from the DOM or create one // and try the `canPlayType` method var video = doc.querySelector("video") || doc.createElement("video"); if (video && video.canPlayType) { return !!video.canPlayType("video/mp4", keyType); } else { return false; } }; requestMediaKeySystemAccess = function (keyType, keySystemConfigurations) { if (!isTypeSupported(keyType)) return Promise_.reject(); for (var i = 0; i < keySystemConfigurations.length; i++) { var keySystemConfiguration = keySystemConfigurations[i]; var videoCapabilities = keySystemConfiguration.videoCapabilities; var audioCapabilities = keySystemConfiguration.audioCapabilities; var initDataTypes = keySystemConfiguration.initDataTypes; var sessionTypes = keySystemConfiguration.sessionTypes; var distinctiveIdentifier = keySystemConfiguration.distinctiveIdentifier; var persistentState = keySystemConfiguration.persistentState; var supported = true; supported = supported && (!initDataTypes || !!_.find(initDataTypes, function (initDataType) { return initDataType === "cenc"; })); supported = supported && (!sessionTypes || _.filter(sessionTypes, function (sessionType) { return sessionType === "temporary"; }).length === sessionTypes.length); supported = supported && distinctiveIdentifier !== "required"; supported = supported && persistentState !== "required"; if (supported) { var keySystemConfigurationResponse = { videoCapabilities: videoCapabilities, audioCapabilities: audioCapabilities, initDataTypes: ["cenc"], distinctiveIdentifier: "not-allowed", persistentState: "not-allowed", sessionTypes: ["temporary"] }; return Promise_.resolve(new KeySystemAccess(keyType, new MockMediaKeys(keyType), keySystemConfigurationResponse)); } } return Promise_.reject(); }; } // A MediaKeys object exist (or a mock) but no create function is // available. We need to add recent apis using Promises to mock the // most recent MediaKeys apis. // This is for IE11 else if (MediaKeys_ && !requestMediaKeySystemAccess) { var SessionProxy = function SessionProxy(mk) { EventEmitter.call(this); this._mk = mk; }; SessionProxy.prototype = _.extend(EventEmitter.prototype, { generateRequest: wrap(function (initDataType, initData) { var _this2 = this; this._ss = this._mk.memCreateSession("video/mp4", initData); this._con = merge(onKeyMessage(this._ss), onKeyAdded(this._ss), onKeyError(this._ss)).subscribe(function (evt) { return _this2.trigger(evt.type, evt); }); }), update: wrapUpdateWithPromise(function (license, sessionId) { assert(this._ss); this._ss.update(license, sessionId); }, function () { return this._ss; }), close: wrap(function () { if (this._ss) { this._ss.close(); this._ss = null; this._con.dispose(); this._con = null; } }) }); // on IE11, each created session needs to be created on a new // MediaKeys object MediaKeys_.prototype.alwaysRenew = true; MediaKeys_.prototype.memCreateSession = MediaKeys_.prototype.createSession; MediaKeys_.prototype.createSession = function () { return new SessionProxy(this); }; requestMediaKeySystemAccess = function (keyType, keySystemConfigurations) { if (!MediaKeys_.isTypeSupported(keyType)) return Promise_.reject(); for (var i = 0; i < keySystemConfigurations.length; i++) { var keySystemConfiguration = keySystemConfigurations[i]; var videoCapabilities = keySystemConfiguration.videoCapabilities; var audioCapabilities = keySystemConfiguration.audioCapabilities; var initDataTypes = keySystemConfiguration.initDataTypes; var distinctiveIdentifier = keySystemConfiguration.distinctiveIdentifier; var supported = true; supported = supported && (!initDataTypes || _.find(initDataTypes, function (idt) { return idt === "cenc"; })); supported = supported && distinctiveIdentifier !== "required"; if (supported) { var keySystemConfigurationResponse = { videoCapabilities: videoCapabilities, audioCapabilities: audioCapabilities, initDataTypes: ["cenc"], distinctiveIdentifier: "not-allowed", persistentState: "required", sessionTypes: ["temporary", "persistent-license"] }; return Promise_.resolve(new KeySystemAccess(keyType, new MockMediaKeys(keyType), keySystemConfigurationResponse)); } } return Promise_.reject(); }; } if (!MediaKeys_) { var noMediaKeys = function noMediaKeys() { throw new Error("eme: MediaKeys is not available"); }; MediaKeys_ = { create: noMediaKeys, isTypeSupported: noMediaKeys }; } function _setMediaKeys(elt, mk) { if (mk instanceof MockMediaKeys) return mk._setVideo(elt); if (elt.setMediaKeys) return elt.setMediaKeys(mk); if (mk === null) return; if (elt.WebkitSetMediaKeys) return elt.WebkitSetMediaKeys(mk); if (elt.mozSetMediaKeys) return elt.mozSetMediaKeys(mk); // IE11 requires that the video has received metadata // (readyState>=1) before setting metadata. // // TODO: how to handle dispose properly ? if (elt.msSetMediaKeys) { return new Promise_(function (res, rej) { if (elt.readyState >= 1) { elt.msSetMediaKeys(mk); res(); } else { elt.addEventListener("loadedmetatdata", function () { try { elt.msSetMediaKeys(mk); } catch (e) { return rej(e); } finally { elt.removeEventListener("loadedmetatdata"); } res(); }); } }); } throw new Error("compat: cannot find setMediaKeys method"); } var setMediaKeys = function setMediaKeys(elt, mk) { return castToPromise(_setMediaKeys(elt, mk)); }; if (win.WebKitSourceBuffer && !win.WebKitSourceBuffer.prototype.addEventListener) { var SourceBuffer = win.WebKitSourceBuffer; var SBProto = SourceBuffer.prototype; _.extend(SBProto, EventEmitter.prototype); SBProto.__listeners = []; SBProto.appendBuffer = function (data) { if (this.updating) throw new Error("SourceBuffer updating"); this.trigger("updatestart"); this.updating = true; try { this.append(data); } catch (err) { this.__emitUpdate("error", err); return; } this.__emitUpdate("update"); }; SBProto.__emitUpdate = function (eventName, val) { var _this3 = this; setTimeout(function () { _this3.trigger(eventName, val); _this3.updating = false; _this3.trigger("updateend"); }, 0); }; } function requestFullscreen(elt) { if (isFullscreen()) return; if (elt.requestFullscreen) return elt.requestFullscreen(); if (elt.msRequestFullscreen) return elt.msRequestFullscreen(); if (elt.mozRequestFullScreen) return elt.mozRequestFullScreen(); if (elt.webkitRequestFullscreen) return elt.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } function exitFullscreen() { if (!isFullscreen()) return; if (doc.exitFullscreen) return doc.exitFullscreen(); if (doc.msExitFullscreen) return doc.msExitFullscreen(); if (doc.mozCancelFullScreen) return doc.mozCancelFullScreen(); if (doc.webkitExitFullscreen) return doc.webkitExitFullscreen(); } function isFullscreen() { return !!(doc.fullscreenElement || doc.mozFullScreenElement || doc.webkitFullscreenElement || doc.msFullscreenElement); } function visibilityChange() { var prefix; if (doc.hidden != null) prefix = "";else if (doc.mozHidden != null) prefix = "moz";else if (doc.msHidden != null) prefix = "ms";else if (doc.webkitHidden != null) prefix = "webkit"; var hidden = prefix ? prefix + "Hidden" : "hidden"; var visibilityChangeEvent = prefix + "visibilitychange"; return on(doc, visibilityChangeEvent).map(function () { return doc[hidden]; }); } function videoSizeChange() { return on(win, "resize"); } // On IE11, fullscreen change events is called MSFullscreenChange var onFullscreenChange = compatibleListener(["fullscreenchange", "FullscreenChange"], PREFIXES.concat("MS")); module.exports = { HTMLVideoElement_: HTMLVideoElement_, MediaSource_: MediaSource_, isCodecSupported: isCodecSupported, sourceOpen: sourceOpen, loadedMetadata: loadedMetadata, canPlay: canPlay, KeySystemAccess: KeySystemAccess, requestMediaKeySystemAccess: requestMediaKeySystemAccess, setMediaKeys: setMediaKeys, emeEvents: emeEvents, isFullscreen: isFullscreen, onFullscreenChange: onFullscreenChange, requestFullscreen: requestFullscreen, exitFullscreen: exitFullscreen, videoSizeChange: videoSizeChange, visibilityChange: visibilityChange }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _ = __webpack_require__(1); var assert = __webpack_require__(2); // Factor for rounding errors var EPSILON = 1 / 60; function nearlyEqual(a, b) { return Math.abs(a - b) < EPSILON; } function nearlyLt(a, b) { return a - b <= EPSILON; } function bufferedToArray(ranges) { if (_.isArray(ranges)) { return ranges; } var i = -1, l = ranges.length; var a = Array(l); while (++i < l) { a[i] = { start: ranges.start(i), end: ranges.end(i), bitrate: 0 }; } return a; } function isPointInRange(r, point) { return r.start <= point && point < r.end; } function findOverlappingRange(range, others) { for (var i = 0; i < others.length; i++) { if (areOverlappingRanges(range, others[i])) return others[i]; } return null; } function areOverlappingRanges(r1, r2) { return isPointInRange(r1, r2.start) || isPointInRange(r1, r2.end) || isPointInRange(r2, r1.start); } function isContainedInto(r1, r2) { return isPointInRange(r1, r2.start) && isPointInRange(r1, r2.end); } function areContiguousWithRanges(r1, r2) { return nearlyEqual(r2.start, r1.end) || nearlyEqual(r2.end, r1.start); } function unionWithOverlappingOrContiguousRange(r1, r2, bitrate) { var start = Math.min(r1.start, r2.start); var end = Math.max(r1.end, r2.end); return { start: start, end: end, bitrate: bitrate }; } function isOrdered(r1, r2) { return r1.end <= r2.start; } function sameBitrate(r1, r2) { return r1.bitrate === r2.bitrate; } function removeEmptyRanges(ranges) { for (var index = 0; index < ranges.length; index++) { var range = ranges[index]; if (range.start === range.end) ranges.splice(index++, 1); } return ranges; } function mergeContiguousRanges(ranges) { for (var index = 1; index < ranges.length; index++) { var prevRange = ranges[index - 1]; var currRange = ranges[index]; if (sameBitrate(prevRange, currRange) && areContiguousWithRanges(prevRange, currRange)) { var unionRange = unionWithOverlappingOrContiguousRange(prevRange, currRange, currRange.bitrate); ranges.splice(--index, 2, unionRange); } } return ranges; } function insertInto(ranges, bitrate, start, end) { assert(start <= end); if (start == end) return; var addedRange = { start: start, end: end, bitrate: bitrate }; // For each present range check if we need to: // - In case we are overlapping or contiguous: // - if added range has the same bitrate as the overlapped or // contiguous one, we can merge them // - if added range has a different bitrate we need to insert it // in place // - Need to insert in place, we we are completely, not overlapping // and not contiguous in between two ranges. for (var index = 0; index < ranges.length; index++) { var currentRange = ranges[index]; var overlapping = areOverlappingRanges(addedRange, currentRange); var contiguous = areContiguousWithRanges(addedRange, currentRange); // We assume ranges are ordered and two ranges can not be // completely overlapping. if (overlapping || contiguous) { // We need to merge the addedRange and that range. if (sameBitrate(addedRange, currentRange)) { addedRange = unionWithOverlappingOrContiguousRange(addedRange, currentRange, currentRange.bitrate); ranges.splice(index--, 1); } // Overlapping ranges with different bitrates. else if (overlapping) { // Added range is contained in on existing range if (isContainedInto(currentRange, addedRange)) { ranges.splice(++index, 0, addedRange); var memCurrentEnd = currentRange.end; currentRange.end = addedRange.start; addedRange = { start: addedRange.end, end: memCurrentEnd, bitrate: currentRange.bitrate }; } // Added range contains one existing range else if (isContainedInto(addedRange, currentRange)) { ranges.splice(index--, 1); } else if (currentRange.start < addedRange.start) { currentRange.end = addedRange.start; } else { currentRange.start = addedRange.end; break; } } // Contiguous ranges with different bitrates. else { // do nothing break; } } else { // Check the case for which there is no more to do if (index === 0) { if (isOrdered(addedRange, ranges[0])) { // First index, and we are completely before that range (and // not contiguous, nor overlapping). We just need to be // inserted here. break; } } else { if (isOrdered(ranges[index - 1], addedRange) && isOrdered(addedRange, currentRange)) { // We are exactly after the current previous range, and // before the current range, while not overlapping with none // of them. Insert here. break; } } } } // Now that we are sure we don't overlap with any range, just add it. ranges.splice(index, 0, addedRange); return mergeContiguousRanges(removeEmptyRanges(ranges)); } function rangesIntersect(ranges, others) { for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; var overlappingRange = findOverlappingRange(range, others); if (!overlappingRange) { ranges.splice(i--, 1); continue; } if (overlappingRange.start > range.start) { range.start = overlappingRange.start; } if (overlappingRange.end < range.end) { range.end = overlappingRange.end; } } return ranges; } function rangesEquals(ranges, others) { for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; var overlappingRange = findOverlappingRange(range, others); if (!overlappingRange || overlappingRange.start > range.start || overlappingRange.end < range.end) { return false; } } return true; } var BufferedRanges = (function () { function BufferedRanges(ranges) { _classCallCheck(this, BufferedRanges); this.ranges = ranges ? bufferedToArray(ranges) : []; this.length = this.ranges.length; } BufferedRanges.prototype.start = function start(i) { return this.ranges[i].start; }; BufferedRanges.prototype.end = function end(i) { return this.ranges[i].end; }; BufferedRanges.prototype.hasRange = function hasRange(startTime, duration) { var endTime = startTime + duration; for (var i = 0; i < this.ranges.length; i++) { var _ranges$i = this.ranges[i]; var start = _ranges$i.start; var end = _ranges$i.end; if (nearlyLt(start, startTime) && nearlyLt(startTime, end) && nearlyLt(start, endTime) && nearlyLt(endTime, end)) return this.ranges[i]; } return null; }; /** * Get range associated to given time */ BufferedRanges.prototype.getRange = function getRange(time) { for (var i = 0; i < this.ranges.length; i++) { if (isPointInRange(this.ranges[i], time)) return this.ranges[i]; } return null; }; /** * Returns the time-gap between the buffered * end limit and the given timestamp */ BufferedRanges.prototype.getGap = function getGap(time) { var range = this.getRange(time); return range ? range.end - time : Infinity; }; /** * Return the time gap between the current time * and the start of current range. */ BufferedRanges.prototype.getLoaded = function getLoaded(time) { var range = this.getRange(time); return range ? time - range.start : 0; }; /** * Returns the total size of the current range. */ BufferedRanges.prototype.getSize = function getSize(time) { var range = this.getRange(time); return range ? range.end - range.start : 0; }; BufferedRanges.prototype.getNextRangeGap = function getNextRangeGap(time) { var ranges = this.ranges; var i = -1, nextRangeStart; while (++i < ranges.length) { var start = ranges[i].start; if (start > time) { nextRangeStart = start; break; } } if (nextRangeStart != null) return nextRangeStart - time;else return Infinity; }; BufferedRanges.prototype.insert = function insert(bitrate, start, end) { if (false) { assert(start >= 0); assert(end - start > 0); } insertInto(this.ranges, bitrate, start, end); this.length = this.ranges.length; return this.ranges; }; BufferedRanges.prototype.remove = function remove(start, end) { if (false) { assert(start >= 0); assert(end - start > 0); } this.intersect(new BufferedRanges([{ start: 0, end: start }, { start: end, end: Infinity }])); }; BufferedRanges.prototype.equals = function equals(others) { if (false) assert(others instanceof BufferedRanges); return rangesEquals(this.ranges, others.ranges); }; BufferedRanges.prototype.intersect = function intersect(others) { if (false) assert(others instanceof BufferedRanges); rangesIntersect(this.ranges, others.ranges); this.length = this.ranges.length; return this.ranges; }; return BufferedRanges; })(); module.exports = { bufferedToArray: bufferedToArray, BufferedRanges: BufferedRanges }; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(1); var assert = __webpack_require__(2); function EventEmitter() { this.__listeners = {}; } EventEmitter.prototype.addEventListener = function (evt, fn) { assert(typeof fn == "function", "eventemitter: second argument should be a function"); if (!this.__listeners[evt]) this.__listeners[evt] = []; this.__listeners[evt].push(fn); }; EventEmitter.prototype.removeEventListener = function (evt, fn) { if (arguments.length === 0) { this.__listeners = {}; return; } if (!this.__listeners.hasOwnProperty(evt)) return; if (arguments.length === 1) { delete this.__listeners[evt]; return; } var listeners = this.__listeners[evt]; var index = listeners.indexOf(fn); if (~index) listeners.splice(index, 1); if (!listeners.length) delete this.__listeners[evt]; }; EventEmitter.prototype.trigger = function (evt, arg) { if (!this.__listeners.hasOwnProperty(evt)) return; var listeners = this.__listeners[evt].slice(); _.each(listeners, function (listener) { try { listener(arg); } catch (e) { console.error(e, e.stack); } }); }; // aliases EventEmitter.prototype.on = EventEmitter.prototype.addEventListener; EventEmitter.prototype.off = EventEmitter.prototype.removeEventListener; module.exports = EventEmitter; /***/ }, /* 11 */ /***/ function(module, exports) { "use strict"; var schemeRe = /^(?:[a-z]+:)?\/\//i; var selfDirRe = /\/[\.]{1,2}\//; function _normalizeUrl(url) { // fast path if no ./ or ../ are present in the url if (!selfDirRe.test(url)) { return url; } var newUrl = []; var oldUrl = url.split("/"); for (var i = 0, l = oldUrl.length; i < l; i++) { if (oldUrl[i] == "..") { newUrl.pop(); } else if (oldUrl[i] == ".") { continue; } else { newUrl.push(oldUrl[i]); } } return newUrl.join("/"); } function resolveURL() { var len = arguments.length; if (len === 0) return ""; var base = ""; for (var i = 0; i < len; i++) { var part = arguments[i]; if (typeof part !== "string" || part === "") { continue; } if (schemeRe.test(part)) { base = part; } else { if (part[0] === "/") { part = part.substr(1); } if (base[base.length - 1] === "/") { base = base.substr(0, base.length - 1); } base = base + "/" + part; } } return _normalizeUrl(base); } function parseBaseURL(url) { var slash = url.lastIndexOf("/"); if (slash >= 0) { return url.substring(0, slash + 1); } else { return url; } } module.exports = { resolveURL: resolveURL, parseBaseURL: parseBaseURL }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var log = __webpack_require__(4); var assert = __webpack_require__(2); var _require = __webpack_require__(11); var parseBaseURL = _require.parseBaseURL; var _require2 = __webpack_require__(8); var isCodecSupported = _require2.isCodecSupported; var representationBaseType = ["profiles", "width", "height", "frameRate", "audioSamplingRate", "mimeType", "segmentProfiles", "codecs", "maximumSAPPeriod", "maxPlayoutRate", "codingDependency", "index"]; var SUPPORTED_ADAPTATIONS_TYPE = ["audio", "video", "text"]; var DEFAULT_PRESENTATION_DELAY = 15; function parseType(mimeType) { return mimeType.split("/")[0]; } function normalizeManifest(location, manifest, subtitles) { assert(manifest.transportType); manifest.id = manifest.id || _.uniqueId(); manifest.type = manifest.type || "static"; var locations = manifest.locations; if (!locations || !locations.length) { manifest.locations = [location]; } manifest.isLive = manifest.type == "dynamic"; // TODO(pierre): support multi-locations/cdns var urlBase = { rootURL: parseBaseURL(manifest.locations[0]), baseURL: manifest.baseURL, isLive: manifest.isLive }; if (subtitles) { subtitles = normalizeSubtitles(subtitles); } var periods = _.map(manifest.periods, function (period) { return normalizePeriod(period, urlBase, subtitles); }); // TODO(pierre): support multiple periods _.extend(manifest, periods[0]); manifest.periods = null; if (!manifest.duration) manifest.duration = Infinity; if (manifest.isLive) { manifest.suggestedPresentationDelay = manifest.suggestedPresentationDelay || DEFAULT_PRESENTATION_DELAY; manifest.availabilityStartTime = manifest.availabilityStartTime || 0; } return manifest; } function normalizePeriod(period, inherit, subtitles) { period.id = period.id || _.uniqueId(); var adaptations = period.adaptations; adaptations = adaptations.concat(subtitles || []); adaptations = _.map(adaptations, function (ada) { return normalizeAdaptation(ada, inherit); }); adaptations = _.filter(adaptations, function (adaptation) { if (SUPPORTED_ADAPTATIONS_TYPE.indexOf(adaptation.type) < 0) { log.info("not supported adaptation type", adaptation.type); return false; } else { return true; } }); assert(adaptations.length > 0); period.adaptations = _.groupBy(adaptations, "type"); return period; } function normalizeAdaptation(adaptation, inherit) { assert(typeof adaptation.id != "undefined"); _.defaults(adaptation, inherit); var inheritedFromAdaptation = _.pick(adaptation, representationBaseType); var representations = _.map(adaptation.representations, function (rep) { return normalizeRepresentation(rep, inheritedFromAdaptation); }).sort(function (a, b) { return a.bitrate - b.bitrate; }); var type = adaptation.type; var mimeType = adaptation.mimeType; if (!mimeType) mimeType = representations[0].mimeType; assert(mimeType); adaptation.mimeType = mimeType; if (!type) type = adaptation.type = parseType(mimeType); if (type == "video" || type == "audio") { representations = _.filter(representations, function (rep) { return isCodecSupported(getCodec(rep)); }); } assert(representations.length > 0, "manifest: no compatible representation for this adaptation"); adaptation.representations = representations; adaptation.bitrates = _.pluck(representations, "bitrate"); return adaptation; } function normalizeRepresentation(representation, inherit) { assert(typeof representation.id != "undefined"); _.defaults(representation, inherit); var index = representation.index; assert(index); if (!index.timescale) { index.timescale = 1; } if (!representation.bitrate) { representation.bitrate = 1; } // Fix issue in some packagers, like GPAC, generating a non // compliant mimetype with RFC 6381. Other closed-source packagers // maybe impacted. if (representation.codecs == "mp4a.40.02") { representation.codecs = "mp4a.40.2"; } return representation; } function normalizeSubtitles(subtitles) { if (!_.isArray(subtitles)) subtitles = [subtitles]; return _.flatten(subtitles, function (_ref) { var mimeType = _ref.mimeType; var url = _ref.url; var language = _ref.language; var languages = _ref.languages; if (language) { languages = [language]; } return _.map(languages, function (lang) { return { id: _.uniqueId(), type: "text", lang: lang, mimeType: mimeType, rootURL: url, baseURL: "", representations: [{ id: _.uniqueId(), mimeType: mimeType, index: { indexType: "template", duration: Number.MAX_VALUE, timescale: 1, startNumber: 0 } }] }; }); }); } function mergeManifestsIndex(oldManifest, newManifest) { var oldAdaptations = oldManifest.adaptations; var newAdaptations = newManifest.adaptations; for (var type in oldAdaptations) { var oldAdas = oldAdaptations[type]; var newAdas = newAdaptations[type]; _.each(oldAdas, function (a, i) { _.simpleMerge(a.index, newAdas[i].index); }); } return oldManifest; } function mutateManifestLiveGap(manifest) { var addedTime = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1]; if (manifest.isLive) { manifest.presentationLiveGap += addedTime; } } function getCodec(representation) { var codecs = representation.codecs; var mimeType = representation.mimeType; return mimeType + ";codecs=\"" + codecs + "\""; } function getAdaptations(manifest) { var adaptationsByType = manifest.adaptations; if (!adaptationsByType) { return []; } var adaptationsList = []; _.each(_.keys(adaptationsByType), function (type) { var adaptations = adaptationsByType[type]; adaptationsList.push({ type: type, adaptations: adaptations, codec: getCodec(adaptations[0].representations[0]) }); }); return adaptationsList; } function getAdaptationsByType(manifest, type) { var adaptations = manifest.adaptations; var adaptationsForType = adaptations && adaptations[type]; if (adaptationsForType) { return adaptationsForType; } else { return []; } } function getAvailableLanguages(manifest) { return getAdaptationsByType(manifest, "audio").map(function (ada) { return ada.lang; }); } function getAvailableSubtitles(manifest) { return getAdaptationsByType(manifest, "text").map(function (ada) { return ada.lang; }); } function createDirectFileManifest() { return { isLive: false, duration: Infinity, adaptations: null }; } module.exports = { normalizeManifest: normalizeManifest, mergeManifestsIndex: mergeManifestsIndex, mutateManifestLiveGap: mutateManifestLiveGap, getCodec: getCodec, getAdaptations: getAdaptations, getAdaptationsByType: getAdaptationsByType, getAvailableSubtitles: getAvailableSubtitles, getAvailableLanguages: getAvailableLanguages, createDirectFileManifest: createDirectFileManifest }; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {// v3.1.1 // // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. 'use strict';var root=global;var Promise_=__webpack_require__(6);var Rx={internals:{},config:{Promise:Promise_},helpers:{}}; // Defaults var noop=Rx.helpers.noop = function(){},identity=Rx.helpers.identity = function(x){return x;},defaultNow=Rx.helpers.defaultNow = Date.now,defaultComparer=Rx.helpers.defaultComparer = function(x,y){return isEqual(x,y);},defaultSubComparer=Rx.helpers.defaultSubComparer = function(x,y){return x > y?1:x < y?-1:0;},defaultError=Rx.helpers.defaultError = function(err){throw err;},isPromise=Rx.helpers.isPromise = function(p){return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function';},isFunction=Rx.helpers.isFunction = function(value){return typeof value == 'function' || false;};function cloneArray(arr){var len=arr.length,a=new Array(len);for(var i=0;i < len;i++) {a[i] = arr[i];}return a;}var errorObj={e:{}};var tryCatchTarget;function tryCatcher(){try{return tryCatchTarget.apply(this,arguments);}catch(e) {errorObj.e = e;return errorObj;}}function tryCatch(fn){if(!isFunction(fn)){throw new TypeError('fn must be a function');}tryCatchTarget = fn;return tryCatcher;}function thrower(e){throw e;}var EmptyError=Rx.EmptyError = function(){this.message = 'Sequence contains no elements.';this.name = 'EmptyError';Error.call(this);};EmptyError.prototype = Error.prototype;var ObjectDisposedError=Rx.ObjectDisposedError = function(){this.message = 'Object has been disposed';this.name = 'ObjectDisposedError';Error.call(this);};ObjectDisposedError.prototype = Error.prototype;var ArgumentOutOfRangeError=Rx.ArgumentOutOfRangeError = function(){this.message = 'Argument out of range';this.name = 'ArgumentOutOfRangeError';Error.call(this);};ArgumentOutOfRangeError.prototype = Error.prototype;var NotSupportedError=Rx.NotSupportedError = function(message){this.message = message || 'This operation is not supported';this.name = 'NotSupportedError';Error.call(this);};NotSupportedError.prototype = Error.prototype;var NotImplementedError=Rx.NotImplementedError = function(message){this.message = message || 'This operation is not implemented';this.name = 'NotImplementedError';Error.call(this);};NotImplementedError.prototype = Error.prototype;var notImplemented=Rx.helpers.notImplemented = function(){throw new NotImplementedError();};var notSupported=Rx.helpers.notSupported = function(){throw new NotSupportedError();}; // Shim in iterator support var $iterator$='_es6shim_iterator_';var doneEnumerator=Rx.doneEnumerator = {done:true,value:undefined};var isArrayLike=Rx.helpers.isArrayLike = function(o){return o && o.length !== undefined;};var bindCallback=Rx.internals.bindCallback = function(func,thisArg,argCount){if(!thisArg){return func;}return function(){return func.apply(thisArg,arguments);};};var isObject=Rx.internals.isObject = function(value){var type=typeof value;return value && (type == 'function' || type == 'object') || false;};var isEqual=Rx.internals.isEqual = function(objA,objB){if(objA === objB){return true;}if(!objA || !objB){return false;}if(typeof objA !== 'object' || typeof objB !== 'object'){return false;}var key; // Test for A's keys different from B. for(key in objA) {if(objA.hasOwnProperty(key) && (!objB.hasOwnProperty(key) || objA[key] !== objB[key])){return false;}} // Test for B's keys missing from A. for(key in objB) {if(objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)){return false;}}return true;};var hasProp=({}).hasOwnProperty,slice=Array.prototype.slice;var inherits=Rx.internals.inherits = function(child,parent){function __(){this.constructor = child;}__.prototype = parent.prototype;child.prototype = new __();};var addProperties=Rx.internals.addProperties = function(obj){for(var idx=1,ln=arguments.length;idx < ln;idx++) {var source=arguments[idx];for(var prop in source) {obj[prop] = source[prop];}}};function arrayInitialize(count,factory){var a=new Array(count);for(var i=0;i < count;i++) {a[i] = factory();}return a;} /** * Represents a group of disposable resources that are disposed together. * @constructor */var CompositeDisposable=Rx.CompositeDisposable = function(){var args=[],i,len;if(Array.isArray(arguments[0])){args = arguments[0];len = args.length;}else {len = arguments.length;args = new Array(len);for(i = 0;i < len;i++) {args[i] = arguments[i];}}for(i = 0;i < len;i++) {if(!isDisposable(args[i])){throw new TypeError('Not a disposable');}}this.disposables = args;this.isDisposed = false;this.length = args.length;};var CompositeDisposablePrototype=CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */CompositeDisposablePrototype.add = function(item){if(this.isDisposed){item.dispose();}else {this.disposables.push(item);this.length++;}}; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */CompositeDisposablePrototype.remove = function(item){var shouldDispose=false;if(!this.isDisposed){var idx=this.disposables.indexOf(item);if(idx !== -1){shouldDispose = true;this.disposables.splice(idx,1);this.length--;item.dispose();}}return shouldDispose;}; /** * Disposes all disposables in the group and removes them from the group. */CompositeDisposablePrototype.dispose = function(){if(!this.isDisposed){this.isDisposed = true;var len=this.disposables.length,currentDisposables=new Array(len);for(var i=0;i < len;i++) {currentDisposables[i] = this.disposables[i];}this.disposables = [];this.length = 0;for(i = 0;i < len;i++) {currentDisposables[i].dispose();}}}; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */var Disposable=Rx.Disposable = function(action){this.isDisposed = false;this.action = action || noop;}; /** Performs the task of cleaning up resources. */Disposable.prototype.dispose = function(){if(!this.isDisposed){this.action();this.isDisposed = true;}}; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */var disposableCreate=Disposable.create = function(action){return new Disposable(action);}; /** * Gets the disposable that does nothing when disposed. */var disposableEmpty=Disposable.empty = {dispose:noop}; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */var isDisposable=Disposable.isDisposable = function(d){return d && isFunction(d.dispose);};var checkDisposed=Disposable.checkDisposed = function(disposable){if(disposable.isDisposed){throw new ObjectDisposedError();}}; // Single assignment var SingleAssignmentDisposable=Rx.SingleAssignmentDisposable = function(){this.isDisposed = false;this.current = null;};SingleAssignmentDisposable.prototype.getDisposable = function(){return this.current;};SingleAssignmentDisposable.prototype.setDisposable = function(value){if(this.current){throw new Error('Disposable has already been assigned');}var shouldDispose=this.isDisposed;!shouldDispose && (this.current = value);shouldDispose && value && value.dispose();};SingleAssignmentDisposable.prototype.dispose = function(){if(!this.isDisposed){this.isDisposed = true;var old=this.current;this.current = null;}old && old.dispose();}; // Multiple assignment disposable var SerialDisposable=Rx.SerialDisposable = function(){this.isDisposed = false;this.current = null;};SerialDisposable.prototype.getDisposable = function(){return this.current;};SerialDisposable.prototype.setDisposable = function(value){var shouldDispose=this.isDisposed;if(!shouldDispose){var old=this.current;this.current = value;}old && old.dispose();shouldDispose && value && value.dispose();};SerialDisposable.prototype.dispose = function(){if(!this.isDisposed){this.isDisposed = true;var old=this.current;this.current = null;}old && old.dispose();}; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */var RefCountDisposable=Rx.RefCountDisposable = (function(){function InnerDisposable(disposable){this.disposable = disposable;this.disposable.count++;this.isInnerDisposed = false;}InnerDisposable.prototype.dispose = function(){if(!this.disposable.isDisposed && !this.isInnerDisposed){this.isInnerDisposed = true;this.disposable.count--;if(this.disposable.count === 0 && this.disposable.isPrimaryDisposed){this.disposable.isDisposed = true;this.disposable.underlyingDisposable.dispose();}}}; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */function RefCountDisposable(disposable){this.underlyingDisposable = disposable;this.isDisposed = false;this.isPrimaryDisposed = false;this.count = 0;} /** * Disposes the underlying disposable only when all dependent disposables have been disposed */RefCountDisposable.prototype.dispose = function(){if(!this.isDisposed && !this.isPrimaryDisposed){this.isPrimaryDisposed = true;if(this.count === 0){this.isDisposed = true;this.underlyingDisposable.dispose();}}}; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */RefCountDisposable.prototype.getDisposable = function(){return this.isDisposed?disposableEmpty:new InnerDisposable(this);};return RefCountDisposable;})();var ScheduledItem=Rx.internals.ScheduledItem = function(scheduler,state,action,dueTime,comparer){this.scheduler = scheduler;this.state = state;this.action = action;this.dueTime = dueTime;this.comparer = comparer || defaultSubComparer;this.disposable = new SingleAssignmentDisposable();};ScheduledItem.prototype.invoke = function(){this.disposable.setDisposable(this.invokeCore());};ScheduledItem.prototype.compareTo = function(other){return this.comparer(this.dueTime,other.dueTime);};ScheduledItem.prototype.isCancelled = function(){return this.disposable.isDisposed;};ScheduledItem.prototype.invokeCore = function(){return this.action(this.scheduler,this.state);}; /** Provides a set of static properties to access commonly used schedulers. */var Scheduler=Rx.Scheduler = (function(){function Scheduler(now,schedule,scheduleRelative,scheduleAbsolute){this.now = now;this._schedule = schedule;this._scheduleRelative = scheduleRelative;this._scheduleAbsolute = scheduleAbsolute;} /** Determines whether the given object is a scheduler */Scheduler.isScheduler = function(s){return s instanceof Scheduler;};function invokeAction(scheduler,action){action();return disposableEmpty;}var schedulerProto=Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.schedule = function(action){return this._schedule(action,invokeAction);}; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleWithState = function(state,action){return this._schedule(state,action);}; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleWithRelative = function(dueTime,action){return this._scheduleRelative(action,dueTime,invokeAction);}; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleWithRelativeAndState = function(state,dueTime,action){return this._scheduleRelative(state,dueTime,action);}; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleWithAbsolute = function(dueTime,action){return this._scheduleAbsolute(action,dueTime,invokeAction);}; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleWithAbsoluteAndState = function(state,dueTime,action){return this._scheduleAbsolute(state,dueTime,action);}; /** Gets the current time according to the local machine's system clock. */Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */Scheduler.normalize = function(timeSpan){timeSpan < 0 && (timeSpan = 0);return timeSpan;};return Scheduler;})();var normalizeTime=Scheduler.normalize,isScheduler=Scheduler.isScheduler;(function(schedulerProto){function invokeRecImmediate(scheduler,pair){var state=pair[0],action=pair[1],group=new CompositeDisposable();action(state,innerAction);return group;function innerAction(state2){var isAdded=false,isDone=false;var d=scheduler.scheduleWithState(state2,scheduleWork);if(!isDone){group.add(d);isAdded = true;}function scheduleWork(_,state3){if(isAdded){group.remove(d);}else {isDone = true;}action(state3,innerAction);return disposableEmpty;}}}function invokeRecDate(scheduler,pair,method){var state=pair[0],action=pair[1],group=new CompositeDisposable();action(state,innerAction);return group;function innerAction(state2,dueTime1){var isAdded=false,isDone=false;var d=scheduler[method](state2,dueTime1,scheduleWork);if(!isDone){group.add(d);isAdded = true;}function scheduleWork(_,state3){if(isAdded){group.remove(d);}else {isDone = true;}action(state3,innerAction);return disposableEmpty;}}}function invokeRecDateRelative(s,p){return invokeRecDate(s,p,'scheduleWithRelativeAndState');}function invokeRecDateAbsolute(s,p){return invokeRecDate(s,p,'scheduleWithAbsoluteAndState');}function scheduleInnerRecursive(action,self){action(function(dt){self(action,dt);});} /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleRecursive = function(action){return this.scheduleRecursiveWithState(action,scheduleInnerRecursive);}; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleRecursiveWithState = function(state,action){return this.scheduleWithState([state,action],invokeRecImmediate);}; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleRecursiveWithRelative = function(dueTime,action){return this.scheduleRecursiveWithRelativeAndState(action,dueTime,scheduleInnerRecursive);}; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleRecursiveWithRelativeAndState = function(state,dueTime,action){return this._scheduleRelative([state,action],dueTime,invokeRecDateRelative);}; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleRecursiveWithAbsolute = function(dueTime,action){return this.scheduleRecursiveWithAbsoluteAndState(action,dueTime,scheduleInnerRecursive);}; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */schedulerProto.scheduleRecursiveWithAbsoluteAndState = function(state,dueTime,action){return this._scheduleAbsolute([state,action],dueTime,invokeRecDateAbsolute);};})(Scheduler.prototype);(function(schedulerProto){ /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */Scheduler.prototype.schedulePeriodic = function(period,action){return this.schedulePeriodicWithState(null,period,action);}; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */Scheduler.prototype.schedulePeriodicWithState = function(state,period,action){if(typeof root.setInterval === 'undefined'){throw new NotSupportedError();}period = normalizeTime(period);var s=state,id=root.setInterval(function(){s = action(s);},period);return disposableCreate(function(){root.clearInterval(id);});};})(Scheduler.prototype); /** Gets a scheduler that schedules work immediately on the current thread. */var immediateScheduler=Scheduler.immediate = (function(){function scheduleNow(state,action){return action(this,state);}return new Scheduler(defaultNow,scheduleNow,notSupported,notSupported);})(); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */var currentThreadScheduler=Scheduler.currentThread = (function(){var queue;function runTrampoline(){while(queue.length > 0) {var item=queue.shift();!item.isCancelled() && item.invoke();}}function scheduleNow(state,action){var si=new ScheduledItem(this,state,action,this.now());if(!queue){queue = [si];var result=tryCatch(runTrampoline)();queue = null;if(result === errorObj){return thrower(result.e);}}else {queue.push(si);}return si.disposable;}var currentScheduler=new Scheduler(defaultNow,scheduleNow,notSupported,notSupported);currentScheduler.scheduleRequired = function(){return !queue;};return currentScheduler;})();var SchedulePeriodicRecursive=Rx.internals.SchedulePeriodicRecursive = (function(){function tick(command,recurse){recurse(0,this._period);try{this._state = this._action(this._state);}catch(e) {this._cancel.dispose();throw e;}}function SchedulePeriodicRecursive(scheduler,state,period,action){this._scheduler = scheduler;this._state = state;this._period = period;this._action = action;}SchedulePeriodicRecursive.prototype.start = function(){var d=new SingleAssignmentDisposable();this._cancel = d;d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,tick.bind(this)));return d;};return SchedulePeriodicRecursive;})();var scheduleMethod,clearMethod;var localTimer=(function(){var localSetTimeout,localClearTimeout=noop;if(!!root.setTimeout){localSetTimeout = root.setTimeout;localClearTimeout = root.clearTimeout;}else if(!!root.WScript){localSetTimeout = function(fn,time){root.WScript.Sleep(time);fn();};}else {throw new NotSupportedError();}return {setTimeout:localSetTimeout,clearTimeout:localClearTimeout};})();var localSetTimeout=localTimer.setTimeout,localClearTimeout=localTimer.clearTimeout;(function(){var nextHandle=1,tasksByHandle={},currentlyRunning=false;clearMethod = function(handle){delete tasksByHandle[handle];};function runTask(handle){if(currentlyRunning){localSetTimeout(function(){runTask(handle);},0);}else {var task=tasksByHandle[handle];if(task){currentlyRunning = true;var result=tryCatch(task)();clearMethod(handle);currentlyRunning = false;if(result === errorObj){return thrower(result.e);}}}}var reNative=RegExp('^' + String(toString).replace(/[.*+?^${}()|[\]\\]/g,'\\$&').replace(/toString| for [^\]]+/g,'.*?') + '$');var setImmediate=global.setImmediate;function postMessageSupported(){ // Ensure not in a worker if(!root.postMessage || root.importScripts){return false;}var isAsync=false,oldHandler=root.onmessage; // Test for async root.onmessage = function(){isAsync = true;};root.postMessage('','*');root.onmessage = oldHandler;return isAsync;} // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if(isFunction(setImmediate)){scheduleMethod = function(action){var id=nextHandle++;tasksByHandle[id] = action;setImmediate(function(){runTask(id);});return id;};}else if(typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'){scheduleMethod = function(action){var id=nextHandle++;tasksByHandle[id] = action;process.nextTick(function(){runTask(id);});return id;};}else if(postMessageSupported()){var onGlobalPostMessage=function onGlobalPostMessage(event){ // Only if we're a match to avoid any other global events if(typeof event.data === 'string' && event.data.substring(0,MSG_PREFIX.length) === MSG_PREFIX){runTask(event.data.substring(MSG_PREFIX.length));}};var MSG_PREFIX='ms.rx.schedule' + Math.random();if(root.addEventListener){root.addEventListener('message',onGlobalPostMessage,false);}else if(root.attachEvent){root.attachEvent('onmessage',onGlobalPostMessage);}else {root.onmessage = onGlobalPostMessage;}scheduleMethod = function(action){var id=nextHandle++;tasksByHandle[id] = action;root.postMessage(MSG_PREFIX + currentId,'*');return id;};}else if(!!root.MessageChannel){var channel=new root.MessageChannel();channel.port1.onmessage = function(e){runTask(e.data);};scheduleMethod = function(action){var id=nextHandle++;tasksByHandle[id] = action;channel.port2.postMessage(id);return id;};}else if('document' in root && 'onreadystatechange' in root.document.createElement('script')){scheduleMethod = function(action){var scriptElement=root.document.createElement('script');var id=nextHandle++;tasksByHandle[id] = action;scriptElement.onreadystatechange = function(){runTask(id);scriptElement.onreadystatechange = null;scriptElement.parentNode.removeChild(scriptElement);scriptElement = null;};root.document.documentElement.appendChild(scriptElement);return id;};}else {scheduleMethod = function(action){var id=nextHandle++;tasksByHandle[id] = action;localSetTimeout(function(){runTask(id);},0);return id;};}})(); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */var timeoutScheduler=Scheduler.timeout = Scheduler['default'] = (function(){function scheduleNow(state,action){var scheduler=this,disposable=new SingleAssignmentDisposable();var id=scheduleMethod(function(){!disposable.isDisposed && disposable.setDisposable(action(scheduler,state));});return new CompositeDisposable(disposable,disposableCreate(function(){clearMethod(id);}));}function scheduleRelative(state,dueTime,action){var scheduler=this,dt=Scheduler.normalize(dueTime),disposable=new SingleAssignmentDisposable();if(dt === 0){return scheduler.scheduleWithState(state,action);}var id=localSetTimeout(function(){!disposable.isDisposed && disposable.setDisposable(action(scheduler,state));},dt);return new CompositeDisposable(disposable,disposableCreate(function(){localClearTimeout(id);}));}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime - this.now(),action);}return new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute);})(); /** * Represents a notification to an observer. */var Notification=Rx.Notification = (function(){function Notification(kind,value,exception,accept,acceptObservable,toString){this.kind = kind;this.value = value;this.exception = exception;this._accept = accept;this._acceptObservable = acceptObservable;this.toString = toString;} /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */Notification.prototype.accept = function(observerOrOnNext,onError,onCompleted){return observerOrOnNext && typeof observerOrOnNext === 'object'?this._acceptObservable(observerOrOnNext):this._accept(observerOrOnNext,onError,onCompleted);}; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */Notification.prototype.toObservable = function(scheduler){var self=this;isScheduler(scheduler) || (scheduler = immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.scheduleWithState(self,function(_,notification){notification._acceptObservable(observer);notification.kind === 'N' && observer.onCompleted();});});};return Notification;})(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */var notificationCreateOnNext=Notification.createOnNext = (function(){function _accept(onNext){return onNext(this.value);}function _acceptObservable(observer){return observer.onNext(this.value);}function toString(){return 'OnNext(' + this.value + ')';}return function(value){return new Notification('N',value,null,_accept,_acceptObservable,toString);};})(); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */var notificationCreateOnError=Notification.createOnError = (function(){function _accept(onNext,onError){return onError(this.exception);}function _acceptObservable(observer){return observer.onError(this.exception);}function toString(){return 'OnError(' + this.exception + ')';}return function(e){return new Notification('E',null,e,_accept,_acceptObservable,toString);};})(); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */var notificationCreateOnCompleted=Notification.createOnCompleted = (function(){function _accept(onNext,onError,onCompleted){return onCompleted();}function _acceptObservable(observer){return observer.onCompleted();}function toString(){return 'OnCompleted()';}return function(){return new Notification('C',null,null,_accept,_acceptObservable,toString);};})(); /** * Supports push-style iteration over an observable sequence. */var Observer=Rx.Observer = function(){}; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */var observerCreate=Observer.create = function(onNext,onError,onCompleted){onNext || (onNext = noop);onError || (onError = defaultError);onCompleted || (onCompleted = noop);return new AnonymousObserver(onNext,onError,onCompleted);}; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */var AbstractObserver=Rx.internals.AbstractObserver = (function(__super__){inherits(AbstractObserver,__super__); /** * Creates a new observer in a non-stopped state. */function AbstractObserver(){this.isStopped = false;} // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented;AbstractObserver.prototype.error = notImplemented;AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */AbstractObserver.prototype.onNext = function(value){!this.isStopped && this.next(value);}; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */AbstractObserver.prototype.onError = function(error){if(!this.isStopped){this.isStopped = true;this.error(error);}}; /** * Notifies the observer of the end of the sequence. */AbstractObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.completed();}}; /** * Disposes the observer, causing it to transition to the stopped state. */AbstractObserver.prototype.dispose = function(){this.isStopped = true;};AbstractObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.error(e);return true;}return false;};return AbstractObserver;})(Observer); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */var AnonymousObserver=Rx.AnonymousObserver = (function(__super__){inherits(AnonymousObserver,__super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */function AnonymousObserver(onNext,onError,onCompleted){__super__.call(this);this._onNext = onNext;this._onError = onError;this._onCompleted = onCompleted;} /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */AnonymousObserver.prototype.next = function(value){this._onNext(value);}; /** * Calls the onError action. * @param {Any} error The error that has occurred. */AnonymousObserver.prototype.error = function(error){this._onError(error);}; /** * Calls the onCompleted action. */AnonymousObserver.prototype.completed = function(){this._onCompleted();};return AnonymousObserver;})(AbstractObserver);var observableProto; /** * Represents a push-style collection. */var Observable=Rx.Observable = (function(){function makeSubscribe(self,subscribe){return function(o){var oldOnError=o.onError;o.onError = function(e){makeStackTraceLong(e,self);oldOnError.call(o,e);};return subscribe.call(self,o);};}function Observable(subscribe){this._subscribe = subscribe;}observableProto = Observable.prototype; /** * Determines whether the given object is an Observable * @param {Any} An object to determine whether it is an Observable * @returns {Boolean} true if an Observable, else false. */Observable.isObservable = function(o){return o && isFunction(o.subscribe);}; /** * Subscribes an o to the observable sequence. * @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */observableProto.subscribe = observableProto.forEach = function(oOrOnNext,onError,onCompleted){return this._subscribe(typeof oOrOnNext === 'object'?oOrOnNext:observerCreate(oOrOnNext,onError,onCompleted));}; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */observableProto.subscribeOnNext = function(onNext,thisArg){return this._subscribe(observerCreate(typeof thisArg !== 'undefined'?function(x){onNext.call(thisArg,x);}:onNext));}; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */observableProto.subscribeOnError = function(onError,thisArg){return this._subscribe(observerCreate(null,typeof thisArg !== 'undefined'?function(e){onError.call(thisArg,e);}:onError));}; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */observableProto.subscribeOnCompleted = function(onCompleted,thisArg){return this._subscribe(observerCreate(null,null,typeof thisArg !== 'undefined'?function(){onCompleted.call(thisArg);}:onCompleted));};return Observable;})();var ScheduledObserver=Rx.internals.ScheduledObserver = (function(__super__){inherits(ScheduledObserver,__super__);function ScheduledObserver(scheduler,observer){__super__.call(this);this.scheduler = scheduler;this.observer = observer;this.isAcquired = false;this.hasFaulted = false;this.queue = [];this.disposable = new SerialDisposable();}ScheduledObserver.prototype.next = function(value){var self=this;this.queue.push(function(){self.observer.onNext(value);});};ScheduledObserver.prototype.error = function(e){var self=this;this.queue.push(function(){self.observer.onError(e);});};ScheduledObserver.prototype.completed = function(){var self=this;this.queue.push(function(){self.observer.onCompleted();});};ScheduledObserver.prototype.ensureActive = function(){var isOwner=false;if(!this.hasFaulted && this.queue.length > 0){isOwner = !this.isAcquired;this.isAcquired = true;}if(isOwner){this.disposable.setDisposable(this.scheduler.scheduleRecursiveWithState(this,function(parent,self){var work;if(parent.queue.length > 0){work = parent.queue.shift();}else {parent.isAcquired = false;return;}var res=tryCatch(work)();if(res === errorObj){parent.queue = [];parent.hasFaulted = true;return thrower(res.e);}self(parent);}));}};ScheduledObserver.prototype.dispose = function(){__super__.prototype.dispose.call(this);this.disposable.dispose();};return ScheduledObserver;})(AbstractObserver);var ObservableBase=Rx.ObservableBase = (function(__super__){inherits(ObservableBase,__super__);function fixSubscriber(subscriber){return subscriber && isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty;}function setDisposable(s,state){var ado=state[0],self=state[1];var sub=tryCatch(self.subscribeCore).call(self,ado);if(sub === errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e);}}ado.setDisposable(fixSubscriber(sub));}function subscribe(observer){var ado=new AutoDetachObserver(observer),state=[ado,this];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable);}else {setDisposable(null,state);}return ado;}function ObservableBase(){__super__.call(this,subscribe);}ObservableBase.prototype.subscribeCore = notImplemented;return ObservableBase;})(Observable);var FlatMapObservable=(function(__super__){inherits(FlatMapObservable,__super__);function FlatMapObservable(source,selector,resultSelector,thisArg){this.resultSelector = Rx.helpers.isFunction(resultSelector)?resultSelector:null;this.selector = Rx.internals.bindCallback(Rx.helpers.isFunction(selector)?selector:function(){return selector;},thisArg,3);this.source = source;__super__.call(this);}FlatMapObservable.prototype.subscribeCore = function(o){return this.source.subscribe(new InnerObserver(o,this.selector,this.resultSelector,this));};function InnerObserver(observer,selector,resultSelector,source){this.i = 0;this.selector = selector;this.resultSelector = resultSelector;this.source = source;this.isStopped = false;this.o = observer;}InnerObserver.prototype._wrapResult = function(result,x,i){return this.resultSelector?result.map(function(y,i2){return this.resultSelector(x,y,i,i2);},this):result;};InnerObserver.prototype.onNext = function(x){if(this.isStopped)return;var i=this.i++;var result=tryCatch(this.selector)(x,i,this.source);if(result === errorObj){return this.o.onError(result.e);}Rx.helpers.isPromise(result) && (result = Rx.Observable.fromPromise(result));Rx.helpers.isArrayLike(result) && (result = Rx.Observable.from(result));this.o.onNext(this._wrapResult(result,x,i));};InnerObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.o.onCompleted();}};return FlatMapObservable;})(ObservableBase);var Enumerable=Rx.internals.Enumerable = function(){};var ConcatEnumerableObservable=(function(__super__){inherits(ConcatEnumerableObservable,__super__);function ConcatEnumerableObservable(sources){this.sources = sources;__super__.call(this);}ConcatEnumerableObservable.prototype.subscribeCore = function(o){var isDisposed,subscription=new SerialDisposable();var cancelable=immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](),function(e,self){if(isDisposed){return;}var currentItem=tryCatch(e.next).call(e);if(currentItem === errorObj){return o.onError(currentItem.e);}if(currentItem.done){return o.onCompleted();} // Check if promise var currentValue=currentItem.value;isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));var d=new SingleAssignmentDisposable();subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(new InnerObserver(o,self,e)));});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed = true;}));};function InnerObserver(o,s,e){this.o = o;this.s = s;this.e = e;this.isStopped = false;}InnerObserver.prototype.onNext = function(x){if(!this.isStopped){this.o.onNext(x);}};InnerObserver.prototype.onError = function(err){if(!this.isStopped){this.isStopped = true;this.o.onError(err);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.s(this.e);}};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(err){if(!this.isStopped){this.isStopped = true;this.o.onError(err);return true;}return false;};return ConcatEnumerableObservable;})(ObservableBase);Enumerable.prototype.concat = function(){return new ConcatEnumerableObservable(this);};var CatchErrorObservable=(function(__super__){inherits(CatchErrorObservable,__super__);function CatchErrorObservable(sources){this.sources = sources;__super__.call(this);}CatchErrorObservable.prototype.subscribeCore = function(o){var e=this.sources[$iterator$]();var isDisposed,subscription=new SerialDisposable();var cancelable=immediateScheduler.scheduleRecursiveWithState(null,function(lastException,self){if(isDisposed){return;}var currentItem=tryCatch(e.next).call(e);if(currentItem === errorObj){return o.onError(currentItem.e);}if(currentItem.done){return lastException !== null?o.onError(lastException):o.onCompleted();} // Check if promise var currentValue=currentItem.value;isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));var d=new SingleAssignmentDisposable();subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(function(x){o.onNext(x);},self,function(){o.onCompleted();}));});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed = true;}));};return CatchErrorObservable;})(ObservableBase);Enumerable.prototype.catchError = function(){return new CatchErrorObservable(this);};Enumerable.prototype.catchErrorWhen = function(notificationHandler){var sources=this;return new AnonymousObservable(function(o){var exceptions=new Subject(),notifier=new Subject(),handled=notificationHandler(exceptions),notificationDisposable=handled.subscribe(notifier);var e=sources[$iterator$]();var isDisposed,lastException,subscription=new SerialDisposable();var cancelable=immediateScheduler.scheduleRecursive(function(self){if(isDisposed){return;}var currentItem=tryCatch(e.next).call(e);if(currentItem === errorObj){return o.onError(currentItem.e);}if(currentItem.done){if(lastException){o.onError(lastException);}else {o.onCompleted();}return;} // Check if promise var currentValue=currentItem.value;isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));var outer=new SingleAssignmentDisposable();var inner=new SingleAssignmentDisposable();subscription.setDisposable(new CompositeDisposable(inner,outer));outer.setDisposable(currentValue.subscribe(function(x){o.onNext(x);},function(exn){inner.setDisposable(notifier.subscribe(self,function(ex){o.onError(ex);},function(){o.onCompleted();}));exceptions.onNext(exn);},function(){o.onCompleted();}));});return new CompositeDisposable(notificationDisposable,subscription,cancelable,disposableCreate(function(){isDisposed = true;}));});};var RepeatEnumerable=(function(__super__){inherits(RepeatEnumerable,__super__);function RepeatEnumerable(v,c){this.v = v;this.c = c == null?-1:c;}RepeatEnumerable.prototype[$iterator$] = function(){return new RepeatEnumerator(this);};function RepeatEnumerator(p){this.v = p.v;this.l = p.c;}RepeatEnumerator.prototype.next = function(){if(this.l === 0){return doneEnumerator;}if(this.l > 0){this.l--;}return {done:false,value:this.v};};return RepeatEnumerable;})(Enumerable);var enumerableRepeat=Enumerable.repeat = function(value,repeatCount){return new RepeatEnumerable(value,repeatCount);};var OfEnumerable=(function(__super__){inherits(OfEnumerable,__super__);function OfEnumerable(s,fn,thisArg){this.s = s;this.fn = fn?bindCallback(fn,thisArg,3):null;}OfEnumerable.prototype[$iterator$] = function(){return new OfEnumerator(this);};function OfEnumerator(p){this.i = -1;this.s = p.s;this.l = this.s.length;this.fn = p.fn;}OfEnumerator.prototype.next = function(){return ++this.i < this.l?{done:false,value:!this.fn?this.s[this.i]:this.fn(this.s[this.i],this.i,this.s)}:doneEnumerator;};return OfEnumerable;})(Enumerable);var enumerableOf=Enumerable.of = function(source,selector,thisArg){return new OfEnumerable(source,selector,thisArg);};var ToArrayObservable=(function(__super__){inherits(ToArrayObservable,__super__);function ToArrayObservable(source){this.source = source;__super__.call(this);}ToArrayObservable.prototype.subscribeCore = function(o){return this.source.subscribe(new InnerObserver(o));};function InnerObserver(o){this.o = o;this.a = [];this.isStopped = false;}InnerObserver.prototype.onNext = function(x){if(!this.isStopped){this.a.push(x);}};InnerObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.o.onNext(this.a);this.o.onCompleted();}};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);return true;}return false;};return ToArrayObservable;})(ObservableBase); /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */observableProto.toArray = function(){return new ToArrayObservable(this);}; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */Observable.create = function(subscribe,parent){return new AnonymousObservable(subscribe,parent);}; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */var observableDefer=Observable.defer = function(observableFactory){return new AnonymousObservable(function(observer){var result;try{result = observableFactory();}catch(e) {return observableThrow(e).subscribe(observer);}isPromise(result) && (result = observableFromPromise(result));return result.subscribe(observer);});};var EmptyObservable=(function(__super__){inherits(EmptyObservable,__super__);function EmptyObservable(scheduler){this.scheduler = scheduler;__super__.call(this);}EmptyObservable.prototype.subscribeCore = function(observer){var sink=new EmptySink(observer,this.scheduler);return sink.run();};function EmptySink(observer,scheduler){this.observer = observer;this.scheduler = scheduler;}function scheduleItem(s,state){state.onCompleted();return disposableEmpty;}EmptySink.prototype.run = function(){return this.scheduler.scheduleWithState(this.observer,scheduleItem);};return EmptyObservable;})(ObservableBase);var EMPTY_OBSERVABLE=new EmptyObservable(immediateScheduler); /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */var observableEmpty=Observable.empty = function(scheduler){isScheduler(scheduler) || (scheduler = immediateScheduler);return scheduler === immediateScheduler?EMPTY_OBSERVABLE:new EmptyObservable(scheduler);};var FromObservable=(function(__super__){inherits(FromObservable,__super__);function FromObservable(iterable,mapper,scheduler){this.iterable = iterable;this.mapper = mapper;this.scheduler = scheduler;__super__.call(this);}FromObservable.prototype.subscribeCore = function(o){var sink=new FromSink(o,this);return sink.run();};return FromObservable;})(ObservableBase);var FromSink=(function(){function FromSink(o,parent){this.o = o;this.parent = parent;}FromSink.prototype.run = function(){var list=Object(this.parent.iterable),it=getIterable(list),o=this.o,mapper=this.parent.mapper;function loopRecursive(i,recurse){var next=tryCatch(it.next).call(it);if(next === errorObj){return o.onError(next.e);}if(next.done){return o.onCompleted();}var result=next.value;if(isFunction(mapper)){result = tryCatch(mapper)(result,i);if(result === errorObj){return o.onError(result.e);}}o.onNext(result);recurse(i + 1);}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive);};return FromSink;})();var maxSafeInteger=Math.pow(2,53) - 1;function StringIterable(s){this._s = s;}StringIterable.prototype[$iterator$] = function(){return new StringIterator(this._s);};function StringIterator(s){this._s = s;this._l = s.length;this._i = 0;}StringIterator.prototype[$iterator$] = function(){return this;};StringIterator.prototype.next = function(){return this._i < this._l?{done:false,value:this._s.charAt(this._i++)}:doneEnumerator;};function ArrayIterable(a){this._a = a;}ArrayIterable.prototype[$iterator$] = function(){return new ArrayIterator(this._a);};function ArrayIterator(a){this._a = a;this._l = toLength(a);this._i = 0;}ArrayIterator.prototype[$iterator$] = function(){return this;};ArrayIterator.prototype.next = function(){return this._i < this._l?{done:false,value:this._a[this._i++]}:doneEnumerator;};function numberIsFinite(value){return typeof value === 'number' && root.isFinite(value);}function isNan(n){return n !== n;}function getIterable(o){var i=o[$iterator$],it;if(!i && typeof o === 'string'){it = new StringIterable(o);return it[$iterator$]();}if(!i && o.length !== undefined){it = new ArrayIterable(o);return it[$iterator$]();}if(!i){throw new TypeError('Object is not iterable');}return o[$iterator$]();}function sign(value){var number=+value;if(number === 0){return number;}if(isNaN(number)){return number;}return number < 0?-1:1;}function toLength(o){var len=+o.length;if(isNaN(len)){return 0;}if(len === 0 || !numberIsFinite(len)){return len;}len = sign(len) * Math.floor(Math.abs(len));if(len <= 0){return 0;}if(len > maxSafeInteger){return maxSafeInteger;}return len;} /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */var observableFrom=Observable.from = function(iterable,mapFn,thisArg,scheduler){if(iterable == null){throw new Error('iterable cannot be null.');}if(mapFn && !isFunction(mapFn)){throw new Error('mapFn when provided must be a function');}if(mapFn){var mapper=bindCallback(mapFn,thisArg,2);}isScheduler(scheduler) || (scheduler = currentThreadScheduler);return new FromObservable(iterable,mapper,scheduler);};var FromArrayObservable=(function(__super__){inherits(FromArrayObservable,__super__);function FromArrayObservable(args,scheduler){this.args = args;this.scheduler = scheduler;__super__.call(this);}FromArrayObservable.prototype.subscribeCore = function(observer){var sink=new FromArraySink(observer,this);return sink.run();};return FromArrayObservable;})(ObservableBase);function FromArraySink(observer,parent){this.observer = observer;this.parent = parent;}FromArraySink.prototype.run = function(){var observer=this.observer,args=this.parent.args,len=args.length;function loopRecursive(i,recurse){if(i < len){observer.onNext(args[i]);recurse(i + 1);}else {observer.onCompleted();}}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive);}; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */var observableFromArray=Observable.fromArray = function(array,scheduler){isScheduler(scheduler) || (scheduler = currentThreadScheduler);return new FromArrayObservable(array,scheduler);};var NeverObservable=(function(__super__){inherits(NeverObservable,__super__);function NeverObservable(){__super__.call(this);}NeverObservable.prototype.subscribeCore = function(observer){return disposableEmpty;};return NeverObservable;})(ObservableBase);var NEVER_OBSERVABLE=new NeverObservable(); /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */var observableNever=Observable.never = function(){return NEVER_OBSERVABLE;};function observableOf(scheduler,array){isScheduler(scheduler) || (scheduler = currentThreadScheduler);return new FromArrayObservable(array,scheduler);} /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */Observable.of = function(){var len=arguments.length,args=new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}return new FromArrayObservable(args,currentThreadScheduler);}; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */Observable.ofWithScheduler = function(scheduler){var len=arguments.length,args=new Array(len - 1);for(var i=1;i < len;i++) {args[i - 1] = arguments[i];}return new FromArrayObservable(args,scheduler);};var PairsObservable=(function(__super__){inherits(PairsObservable,__super__);function PairsObservable(obj,scheduler){this.obj = obj;this.keys = Object.keys(obj);this.scheduler = scheduler;__super__.call(this);}PairsObservable.prototype.subscribeCore = function(observer){var sink=new PairsSink(observer,this);return sink.run();};return PairsObservable;})(ObservableBase);function PairsSink(observer,parent){this.observer = observer;this.parent = parent;}PairsSink.prototype.run = function(){var observer=this.observer,obj=this.parent.obj,keys=this.parent.keys,len=keys.length;function loopRecursive(i,recurse){if(i < len){var key=keys[i];observer.onNext([key,obj[key]]);recurse(i + 1);}else {observer.onCompleted();}}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive);}; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */Observable.pairs = function(obj,scheduler){scheduler || (scheduler = currentThreadScheduler);return new PairsObservable(obj,scheduler);};var RangeObservable=(function(__super__){inherits(RangeObservable,__super__);function RangeObservable(start,count,scheduler){this.start = start;this.rangeCount = count;this.scheduler = scheduler;__super__.call(this);}RangeObservable.prototype.subscribeCore = function(observer){var sink=new RangeSink(observer,this);return sink.run();};return RangeObservable;})(ObservableBase);var RangeSink=(function(){function RangeSink(observer,parent){this.observer = observer;this.parent = parent;}RangeSink.prototype.run = function(){var start=this.parent.start,count=this.parent.rangeCount,observer=this.observer;function loopRecursive(i,recurse){if(i < count){observer.onNext(start + i);recurse(i + 1);}else {observer.onCompleted();}}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive);};return RangeSink;})(); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */Observable.range = function(start,count,scheduler){isScheduler(scheduler) || (scheduler = currentThreadScheduler);return new RangeObservable(start,count,scheduler);};var RepeatObservable=(function(__super__){inherits(RepeatObservable,__super__);function RepeatObservable(value,repeatCount,scheduler){this.value = value;this.repeatCount = repeatCount == null?-1:repeatCount;this.scheduler = scheduler;__super__.call(this);}RepeatObservable.prototype.subscribeCore = function(observer){var sink=new RepeatSink(observer,this);return sink.run();};return RepeatObservable;})(ObservableBase);function RepeatSink(observer,parent){this.observer = observer;this.parent = parent;}RepeatSink.prototype.run = function(){var observer=this.observer,value=this.parent.value;function loopRecursive(i,recurse){if(i === -1 || i > 0){observer.onNext(value);i > 0 && i--;}if(i === 0){return observer.onCompleted();}recurse(i);}return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount,loopRecursive);}; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */Observable.repeat = function(value,repeatCount,scheduler){isScheduler(scheduler) || (scheduler = currentThreadScheduler);return new RepeatObservable(value,repeatCount,scheduler);};var JustObservable=(function(__super__){inherits(JustObservable,__super__);function JustObservable(value,scheduler){this.value = value;this.scheduler = scheduler;__super__.call(this);}JustObservable.prototype.subscribeCore = function(observer){var sink=new JustSink(observer,this.value,this.scheduler);return sink.run();};function JustSink(observer,value,scheduler){this.observer = observer;this.value = value;this.scheduler = scheduler;}function scheduleItem(s,state){var value=state[0],observer=state[1];observer.onNext(value);observer.onCompleted();return disposableEmpty;}JustSink.prototype.run = function(){var state=[this.value,this.observer];return this.scheduler === immediateScheduler?scheduleItem(null,state):this.scheduler.scheduleWithState(state,scheduleItem);};return JustObservable;})(ObservableBase); /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just' or browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */var observableReturn=Observable['return'] = Observable.just = function(value,scheduler){isScheduler(scheduler) || (scheduler = immediateScheduler);return new JustObservable(value,scheduler);};var ThrowObservable=(function(__super__){inherits(ThrowObservable,__super__);function ThrowObservable(error,scheduler){this.error = error;this.scheduler = scheduler;__super__.call(this);}ThrowObservable.prototype.subscribeCore = function(o){var sink=new ThrowSink(o,this);return sink.run();};function ThrowSink(o,p){this.o = o;this.p = p;}function scheduleItem(s,state){var e=state[0],o=state[1];o.onError(e);}ThrowSink.prototype.run = function(){return this.p.scheduler.scheduleWithState([this.p.error,this.o],scheduleItem);};return ThrowObservable;})(ObservableBase); /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */var observableThrow=Observable['throw'] = function(error,scheduler){isScheduler(scheduler) || (scheduler = immediateScheduler);return new ThrowObservable(error,scheduler);};var CatchObserver=(function(__super__){inherits(CatchObserver,__super__);function CatchObserver(o,s,fn){this._o = o;this._s = s;this._fn = fn;__super__.call(this);}CatchObserver.prototype.next = function(x){this._o.onNext(x);};CatchObserver.prototype.completed = function(){return this._o.onCompleted();};CatchObserver.prototype.error = function(e){var result=tryCatch(this._fn)(e);if(result === errorObj){return this._o.onError(result.e);}isPromise(result) && (result = observableFromPromise(result));var d=new SingleAssignmentDisposable();this._s.setDisposable(d);d.setDisposable(result.subscribe(this._o));};return CatchObserver;})(AbstractObserver);function observableCatchHandler(source,handler){return new AnonymousObservable(function(o){var d1=new SingleAssignmentDisposable(),subscription=new SerialDisposable();subscription.setDisposable(d1);d1.setDisposable(source.subscribe(new CatchObserver(o,subscription,handler)));return subscription;},source);} /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */observableProto['catch'] = function(handlerOrSecond){return isFunction(handlerOrSecond)?observableCatchHandler(this,handlerOrSecond):observableCatch([this,handlerOrSecond]);}; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */var observableCatch=Observable['catch'] = function(){var items;if(Array.isArray(arguments[0])){items = arguments[0];}else {var len=arguments.length;items = new Array(len);for(var i=0;i < len;i++) {items[i] = arguments[i];}}return enumerableOf(items).catchError();}; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */observableProto.combineLatest = function(){var len=arguments.length,args=new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}if(Array.isArray(args[0])){args[0].unshift(this);}else {args.unshift(this);}return combineLatest.apply(this,args);};function falseFactory(){return false;}function emptyArrayFactory(){return [];}function argumentsToArray(){var len=arguments.length,args=new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}return args;} /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */var combineLatest=Observable.combineLatest = function(){var len=arguments.length,args=new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}var resultSelector=isFunction(args[len - 1])?args.pop():argumentsToArray;Array.isArray(args[0]) && (args = args[0]);return new AnonymousObservable(function(o){var n=args.length,hasValue=arrayInitialize(n,falseFactory),hasValueAll=false,isDone=arrayInitialize(n,falseFactory),values=new Array(n);function next(i){hasValue[i] = true;if(hasValueAll || (hasValueAll = hasValue.every(identity))){try{var res=resultSelector.apply(null,values);}catch(e) {return o.onError(e);}o.onNext(res);}else if(isDone.filter(function(x,j){return j !== i;}).every(identity)){o.onCompleted();}}function done(i){isDone[i] = true;isDone.every(identity) && o.onCompleted();}var subscriptions=new Array(n);for(var idx=0;idx < n;idx++) {(function(i){var source=args[i],sad=new SingleAssignmentDisposable();isPromise(source) && (source = observableFromPromise(source));sad.setDisposable(source.subscribe(function(x){values[i] = x;next(i);},function(e){o.onError(e);},function(){done(i);}));subscriptions[i] = sad;})(idx);}return new CompositeDisposable(subscriptions);},this);}; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */observableProto.concat = function(){for(var args=[],i=0,len=arguments.length;i < len;i++) {args.push(arguments[i]);}args.unshift(this);return observableConcat.apply(null,args);};var ConcatObservable=(function(__super__){inherits(ConcatObservable,__super__);function ConcatObservable(sources){this.sources = sources;__super__.call(this);}ConcatObservable.prototype.subscribeCore = function(o){var sink=new ConcatSink(this.sources,o);return sink.run();};function ConcatSink(sources,o){this.sources = sources;this.o = o;}ConcatSink.prototype.run = function(){var isDisposed,subscription=new SerialDisposable(),sources=this.sources,length=sources.length,o=this.o;var cancelable=immediateScheduler.scheduleRecursiveWithState(0,function(i,self){if(isDisposed){return;}if(i === length){return o.onCompleted();} // Check if promise var currentValue=sources[i];isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));var d=new SingleAssignmentDisposable();subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(function(x){o.onNext(x);},function(e){o.onError(e);},function(){self(i + 1);}));});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed = true;}));};return ConcatObservable;})(ObservableBase); /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */var observableConcat=Observable.concat = function(){var args;if(Array.isArray(arguments[0])){args = arguments[0];}else {args = new Array(arguments.length);for(var i=0,len=arguments.length;i < len;i++) {args[i] = arguments[i];}}return new ConcatObservable(args);}; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */observableProto.concatAll = function(){return this.merge(1);};var MergeObservable=(function(__super__){inherits(MergeObservable,__super__);function MergeObservable(source,maxConcurrent){this.source = source;this.maxConcurrent = maxConcurrent;__super__.call(this);}MergeObservable.prototype.subscribeCore = function(observer){var g=new CompositeDisposable();g.add(this.source.subscribe(new MergeObserver(observer,this.maxConcurrent,g)));return g;};return MergeObservable;})(ObservableBase);var MergeObserver=(function(){function MergeObserver(o,max,g){this.o = o;this.max = max;this.g = g;this.done = false;this.q = [];this.activeCount = 0;this.isStopped = false;}MergeObserver.prototype.handleSubscribe = function(xs){var sad=new SingleAssignmentDisposable();this.g.add(sad);isPromise(xs) && (xs = observableFromPromise(xs));sad.setDisposable(xs.subscribe(new InnerObserver(this,sad)));};MergeObserver.prototype.onNext = function(innerSource){if(this.isStopped){return;}if(this.activeCount < this.max){this.activeCount++;this.handleSubscribe(innerSource);}else {this.q.push(innerSource);}};MergeObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);}};MergeObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.done = true;this.activeCount === 0 && this.o.onCompleted();}};MergeObserver.prototype.dispose = function(){this.isStopped = true;};MergeObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);return true;}return false;};function InnerObserver(parent,sad){this.parent = parent;this.sad = sad;this.isStopped = false;}InnerObserver.prototype.onNext = function(x){if(!this.isStopped){this.parent.o.onNext(x);}};InnerObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.parent.o.onError(e);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;var parent=this.parent;parent.g.remove(this.sad);if(parent.q.length > 0){parent.handleSubscribe(parent.q.shift());}else {parent.activeCount--;parent.done && parent.activeCount === 0 && parent.o.onCompleted();}}};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.parent.o.onError(e);return true;}return false;};return MergeObserver;})(); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */observableProto.merge = function(maxConcurrentOrOther){return typeof maxConcurrentOrOther !== 'number'?observableMerge(this,maxConcurrentOrOther):new MergeObservable(this,maxConcurrentOrOther);}; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */var observableMerge=Observable.merge = function(){var scheduler,sources=[],i,len=arguments.length;if(!arguments[0]){scheduler = immediateScheduler;for(i = 1;i < len;i++) {sources.push(arguments[i]);}}else if(isScheduler(arguments[0])){scheduler = arguments[0];for(i = 1;i < len;i++) {sources.push(arguments[i]);}}else {scheduler = immediateScheduler;for(i = 0;i < len;i++) {sources.push(arguments[i]);}}if(Array.isArray(sources[0])){sources = sources[0];}return observableOf(scheduler,sources).mergeAll();};var CompositeError=Rx.CompositeError = function(errors){this.name = "NotImplementedError";this.innerErrors = errors;this.message = 'This contains multiple errors. Check the innerErrors';Error.call(this);};CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */Observable.mergeDelayError = function(){var args;if(Array.isArray(arguments[0])){args = arguments[0];}else {var len=arguments.length;args = new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}}var source=observableOf(null,args);return new AnonymousObservable(function(o){var group=new CompositeDisposable(),m=new SingleAssignmentDisposable(),isStopped=false,errors=[];function setCompletion(){if(errors.length === 0){o.onCompleted();}else if(errors.length === 1){o.onError(errors[0]);}else {o.onError(new CompositeError(errors));}}group.add(m);m.setDisposable(source.subscribe(function(innerSource){var innerSubscription=new SingleAssignmentDisposable();group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));innerSubscription.setDisposable(innerSource.subscribe(function(x){o.onNext(x);},function(e){errors.push(e);group.remove(innerSubscription);isStopped && group.length === 1 && setCompletion();},function(){group.remove(innerSubscription);isStopped && group.length === 1 && setCompletion();}));},function(e){errors.push(e);isStopped = true;group.length === 1 && setCompletion();},function(){isStopped = true;group.length === 1 && setCompletion();}));return group;});};var MergeAllObservable=(function(__super__){inherits(MergeAllObservable,__super__);function MergeAllObservable(source){this.source = source;__super__.call(this);}MergeAllObservable.prototype.subscribeCore = function(observer){var g=new CompositeDisposable(),m=new SingleAssignmentDisposable();g.add(m);m.setDisposable(this.source.subscribe(new MergeAllObserver(observer,g)));return g;};function MergeAllObserver(o,g){this.o = o;this.g = g;this.isStopped = false;this.done = false;}MergeAllObserver.prototype.onNext = function(innerSource){if(this.isStopped){return;}var sad=new SingleAssignmentDisposable();this.g.add(sad);isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));sad.setDisposable(innerSource.subscribe(new InnerObserver(this,sad)));};MergeAllObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);}};MergeAllObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.done = true;this.g.length === 1 && this.o.onCompleted();}};MergeAllObserver.prototype.dispose = function(){this.isStopped = true;};MergeAllObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);return true;}return false;};function InnerObserver(parent,sad){this.parent = parent;this.sad = sad;this.isStopped = false;}InnerObserver.prototype.onNext = function(x){if(!this.isStopped){this.parent.o.onNext(x);}};InnerObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.parent.o.onError(e);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){var parent=this.parent;this.isStopped = true;parent.g.remove(this.sad);parent.done && parent.g.length === 1 && parent.o.onCompleted();}};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.parent.o.onError(e);return true;}return false;};return MergeAllObservable;})(ObservableBase); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */observableProto.mergeAll = function(){return new MergeAllObservable(this);}; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */observableProto.skipUntil = function(other){var source=this;return new AnonymousObservable(function(o){var isOpen=false;var disposables=new CompositeDisposable(source.subscribe(function(left){isOpen && o.onNext(left);},function(e){o.onError(e);},function(){isOpen && o.onCompleted();}));isPromise(other) && (other = observableFromPromise(other));var rightSubscription=new SingleAssignmentDisposable();disposables.add(rightSubscription);rightSubscription.setDisposable(other.subscribe(function(){isOpen = true;rightSubscription.dispose();},function(e){o.onError(e);},function(){rightSubscription.dispose();}));return disposables;},source);};var SwitchObservable=(function(__super__){inherits(SwitchObservable,__super__);function SwitchObservable(source){this.source = source;__super__.call(this);}SwitchObservable.prototype.subscribeCore = function(o){var inner=new SerialDisposable(),s=this.source.subscribe(new SwitchObserver(o,inner));return new CompositeDisposable(s,inner);};function SwitchObserver(o,inner){this.o = o;this.inner = inner;this.stopped = false;this.latest = 0;this.hasLatest = false;this.isStopped = false;}SwitchObserver.prototype.onNext = function(innerSource){if(this.isStopped){return;}var d=new SingleAssignmentDisposable(),id=++this.latest;this.hasLatest = true;this.inner.setDisposable(d);isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));d.setDisposable(innerSource.subscribe(new InnerObserver(this,id)));};SwitchObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);}};SwitchObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.stopped = true;!this.hasLatest && this.o.onCompleted();}};SwitchObserver.prototype.dispose = function(){this.isStopped = true;};SwitchObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);return true;}return false;};function InnerObserver(parent,id){this.parent = parent;this.id = id;this.isStopped = false;}InnerObserver.prototype.onNext = function(x){if(this.isStopped){return;}this.parent.latest === this.id && this.parent.o.onNext(x);};InnerObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.parent.latest === this.id && this.parent.o.onError(e);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;if(this.parent.latest === this.id){this.parent.hasLatest = false;this.parent.isStopped && this.parent.o.onCompleted();}}};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.parent.o.onError(e);return true;}return false;};return SwitchObservable;})(ObservableBase); /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */observableProto['switch'] = observableProto.switchLatest = function(){return new SwitchObservable(this);};var TakeUntilObservable=(function(__super__){inherits(TakeUntilObservable,__super__);function TakeUntilObservable(source,other){this.source = source;this.other = isPromise(other)?observableFromPromise(other):other;__super__.call(this);}TakeUntilObservable.prototype.subscribeCore = function(o){return new CompositeDisposable(this.source.subscribe(o),this.other.subscribe(new InnerObserver(o)));};function InnerObserver(o){this.o = o;this.isStopped = false;}InnerObserver.prototype.onNext = function(x){if(this.isStopped){return;}this.o.onCompleted();};InnerObserver.prototype.onError = function(err){if(!this.isStopped){this.isStopped = true;this.o.onError(err);}};InnerObserver.prototype.onCompleted = function(){!this.isStopped && (this.isStopped = true);};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);return true;}return false;};return TakeUntilObservable;})(ObservableBase); /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */observableProto.takeUntil = function(other){return new TakeUntilObservable(this,other);}; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */observableProto.withLatestFrom = function(){var len=arguments.length,args=new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}var resultSelector=args.pop(),source=this;Array.isArray(args[0]) && (args = args[0]);return new AnonymousObservable(function(observer){var n=args.length,hasValue=arrayInitialize(n,falseFactory),hasValueAll=false,values=new Array(n);var subscriptions=new Array(n + 1);for(var idx=0;idx < n;idx++) {(function(i){var other=args[i],sad=new SingleAssignmentDisposable();isPromise(other) && (other = observableFromPromise(other));sad.setDisposable(other.subscribe(function(x){values[i] = x;hasValue[i] = true;hasValueAll = hasValue.every(identity);},function(e){observer.onError(e);},noop));subscriptions[i] = sad;})(idx);}var sad=new SingleAssignmentDisposable();sad.setDisposable(source.subscribe(function(x){var allValues=[x].concat(values);if(!hasValueAll){return;}var res=tryCatch(resultSelector).apply(null,allValues);if(res === errorObj){return observer.onError(res.e);}observer.onNext(res);},function(e){observer.onError(e);},function(){observer.onCompleted();}));subscriptions[n] = sad;return new CompositeDisposable(subscriptions);},this);}; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */observableProto.zip = function(){if(arguments.length === 0){throw new Error('invalid arguments');}var len=arguments.length,args=new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}var resultSelector=isFunction(args[len - 1])?args.pop():argumentsToArray;Array.isArray(args[0]) && (args = args[0]);var parent=this;args.unshift(parent);return new AnonymousObservable(function(o){var n=args.length,queues=arrayInitialize(n,emptyArrayFactory),isDone=arrayInitialize(n,falseFactory);var subscriptions=new Array(n);for(var idx=0;idx < n;idx++) {(function(i){var source=args[i],sad=new SingleAssignmentDisposable();isPromise(source) && (source = observableFromPromise(source));sad.setDisposable(source.subscribe(function(x){queues[i].push(x);if(queues.every(function(x){return x.length > 0;})){var queuedValues=queues.map(function(x){return x.shift();}),res=tryCatch(resultSelector).apply(parent,queuedValues);if(res === errorObj){return o.onError(res.e);}o.onNext(res);}else if(isDone.filter(function(x,j){return j !== i;}).every(identity)){o.onCompleted();}},function(e){o.onError(e);},function(){isDone[i] = true;isDone.every(identity) && o.onCompleted();}));subscriptions[i] = sad;})(idx);}return new CompositeDisposable(subscriptions);},parent);}; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */Observable.zip = function(){var len=arguments.length,args=new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}if(Array.isArray(args[0])){args = isFunction(args[1])?args[0].concat(args[1]):args[0];}var first=args.shift();return first.zip.apply(first,args);}; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */observableProto.zipIterable = function(){if(arguments.length === 0){throw new Error('invalid arguments');}var len=arguments.length,args=new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}var resultSelector=isFunction(args[len - 1])?args.pop():argumentsToArray;var parent=this;args.unshift(parent);return new AnonymousObservable(function(o){var n=args.length,queues=arrayInitialize(n,emptyArrayFactory),isDone=arrayInitialize(n,falseFactory);var subscriptions=new Array(n);for(var idx=0;idx < n;idx++) {(function(i){var source=args[i],sad=new SingleAssignmentDisposable();(isArrayLike(source) || isIterable(source)) && (source = observableFrom(source));sad.setDisposable(source.subscribe(function(x){queues[i].push(x);if(queues.every(function(x){return x.length > 0;})){var queuedValues=queues.map(function(x){return x.shift();}),res=tryCatch(resultSelector).apply(parent,queuedValues);if(res === errorObj){return o.onError(res.e);}o.onNext(res);}else if(isDone.filter(function(x,j){return j !== i;}).every(identity)){o.onCompleted();}},function(e){o.onError(e);},function(){isDone[i] = true;isDone.every(identity) && o.onCompleted();}));subscriptions[i] = sad;})(idx);}return new CompositeDisposable(subscriptions);},parent);};function asObservable(source){return function subscribe(o){return source.subscribe(o);};} /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */observableProto.asObservable = function(){return new AnonymousObservable(asObservable(this),this);}; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */observableProto.dematerialize = function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(function(x){return x.accept(o);},function(e){o.onError(e);},function(){o.onCompleted();});},this);};var DistinctUntilChangedObservable=(function(__super__){inherits(DistinctUntilChangedObservable,__super__);function DistinctUntilChangedObservable(source,keyFn,comparer){this.source = source;this.keyFn = keyFn;this.comparer = comparer;__super__.call(this);}DistinctUntilChangedObservable.prototype.subscribeCore = function(o){return this.source.subscribe(new DistinctUntilChangedObserver(o,this.keyFn,this.comparer));};return DistinctUntilChangedObservable;})(ObservableBase);var DistinctUntilChangedObserver=(function(__super__){inherits(DistinctUntilChangedObserver,__super__);function DistinctUntilChangedObserver(o,keyFn,comparer){this.o = o;this.keyFn = keyFn;this.comparer = comparer;this.hasCurrentKey = false;this.currentKey = null;__super__.call(this);}DistinctUntilChangedObserver.prototype.next = function(x){var key=x,comparerEquals;if(isFunction(this.keyFn)){key = tryCatch(this.keyFn)(x);if(key === errorObj){return this.o.onError(key.e);}}if(this.hasCurrentKey){comparerEquals = tryCatch(this.comparer)(this.currentKey,key);if(comparerEquals === errorObj){return this.o.onError(comparerEquals.e);}}if(!this.hasCurrentKey || !comparerEquals){this.hasCurrentKey = true;this.currentKey = key;this.o.onNext(x);}};DistinctUntilChangedObserver.prototype.error = function(e){this.o.onError(e);};DistinctUntilChangedObserver.prototype.completed = function(){this.o.onCompleted();};return DistinctUntilChangedObserver;})(AbstractObserver); /** * Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer. * @param {Function} [keyFn] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */observableProto.distinctUntilChanged = function(keyFn,comparer){comparer || (comparer = defaultComparer);return new DistinctUntilChangedObservable(this,keyFn,comparer);};var TapObservable=(function(__super__){inherits(TapObservable,__super__);function TapObservable(source,observerOrOnNext,onError,onCompleted){this.source = source;this._oN = observerOrOnNext;this._oE = onError;this._oC = onCompleted;__super__.call(this);}TapObservable.prototype.subscribeCore = function(o){return this.source.subscribe(new InnerObserver(o,this));};function InnerObserver(o,p){this.o = o;this.t = !p._oN || isFunction(p._oN)?observerCreate(p._oN || noop,p._oE || noop,p._oC || noop):p._oN;this.isStopped = false;}InnerObserver.prototype.onNext = function(x){if(this.isStopped){return;}var res=tryCatch(this.t.onNext).call(this.t,x);if(res === errorObj){this.o.onError(res.e);}this.o.onNext(x);};InnerObserver.prototype.onError = function(err){if(!this.isStopped){this.isStopped = true;var res=tryCatch(this.t.onError).call(this.t,err);if(res === errorObj){return this.o.onError(res.e);}this.o.onError(err);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;var res=tryCatch(this.t.onCompleted).call(this.t);if(res === errorObj){return this.o.onError(res.e);}this.o.onCompleted();}};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);return true;}return false;};return TapObservable;})(ObservableBase); /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */observableProto['do'] = observableProto.tap = observableProto.doAction = function(observerOrOnNext,onError,onCompleted){return new TapObservable(this,observerOrOnNext,onError,onCompleted);}; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */observableProto.doOnNext = observableProto.tapOnNext = function(onNext,thisArg){return this.tap(typeof thisArg !== 'undefined'?function(x){onNext.call(thisArg,x);}:onNext);}; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */observableProto.doOnError = observableProto.tapOnError = function(onError,thisArg){return this.tap(noop,typeof thisArg !== 'undefined'?function(e){onError.call(thisArg,e);}:onError);}; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */observableProto.doOnCompleted = observableProto.tapOnCompleted = function(onCompleted,thisArg){return this.tap(noop,null,typeof thisArg !== 'undefined'?function(){onCompleted.call(thisArg);}:onCompleted);}; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */observableProto['finally'] = function(action){var source=this;return new AnonymousObservable(function(observer){var subscription=tryCatch(source.subscribe).call(source,observer);if(subscription === errorObj){action();return thrower(subscription.e);}return disposableCreate(function(){var r=tryCatch(subscription.dispose).call(subscription);action();r === errorObj && thrower(r.e);});},this);};var IgnoreElementsObservable=(function(__super__){inherits(IgnoreElementsObservable,__super__);function IgnoreElementsObservable(source){this.source = source;__super__.call(this);}IgnoreElementsObservable.prototype.subscribeCore = function(o){return this.source.subscribe(new InnerObserver(o));};function InnerObserver(o){this.o = o;this.isStopped = false;}InnerObserver.prototype.onNext = noop;InnerObserver.prototype.onError = function(err){if(!this.isStopped){this.isStopped = true;this.o.onError(err);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.o.onCompleted();}};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.observer.onError(e);return true;}return false;};return IgnoreElementsObservable;})(ObservableBase); /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */observableProto.ignoreElements = function(){return new IgnoreElementsObservable(this);}; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */observableProto.materialize = function(){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(function(value){observer.onNext(notificationCreateOnNext(value));},function(e){observer.onNext(notificationCreateOnError(e));observer.onCompleted();},function(){observer.onNext(notificationCreateOnCompleted());observer.onCompleted();});},source);}; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */observableProto.repeat = function(repeatCount){return enumerableRepeat(this,repeatCount).concat();}; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */observableProto.retry = function(retryCount){return enumerableRepeat(this,retryCount).catchError();}; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */observableProto.retryWhen = function(notifier){return enumerableRepeat(this).catchErrorWhen(notifier);};var ScanObservable=(function(__super__){inherits(ScanObservable,__super__);function ScanObservable(source,accumulator,hasSeed,seed){this.source = source;this.accumulator = accumulator;this.hasSeed = hasSeed;this.seed = seed;__super__.call(this);}ScanObservable.prototype.subscribeCore = function(o){return this.source.subscribe(new InnerObserver(o,this));};return ScanObservable;})(ObservableBase);function InnerObserver(o,parent){this.o = o;this.accumulator = parent.accumulator;this.hasSeed = parent.hasSeed;this.seed = parent.seed;this.hasAccumulation = false;this.accumulation = null;this.hasValue = false;this.isStopped = false;}InnerObserver.prototype = {onNext:function onNext(x){if(this.isStopped){return;}!this.hasValue && (this.hasValue = true);if(this.hasAccumulation){this.accumulation = tryCatch(this.accumulator)(this.accumulation,x);}else {this.accumulation = this.hasSeed?tryCatch(this.accumulator)(this.seed,x):x;this.hasAccumulation = true;}if(this.accumulation === errorObj){return this.o.onError(this.accumulation.e);}this.o.onNext(this.accumulation);},onError:function onError(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);}},onCompleted:function onCompleted(){if(!this.isStopped){this.isStopped = true;!this.hasValue && this.hasSeed && this.o.onNext(this.seed);this.o.onCompleted();}},dispose:function dispose(){this.isStopped = true;},fail:function fail(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);return true;}return false;}}; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */observableProto.scan = function(){var hasSeed=false,seed,accumulator=arguments[0];if(arguments.length === 2){hasSeed = true;seed = arguments[1];}return new ScanObservable(this,accumulator,hasSeed,seed);}; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */observableProto.skipLast = function(count){if(count < 0){throw new ArgumentOutOfRangeError();}var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length > count && o.onNext(q.shift());},function(e){o.onError(e);},function(){o.onCompleted();});},source);}; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */observableProto.startWith = function(){var values,scheduler,start=0;if(!!arguments.length && isScheduler(arguments[0])){scheduler = arguments[0];start = 1;}else {scheduler = immediateScheduler;}for(var args=[],i=start,len=arguments.length;i < len;i++) {args.push(arguments[i]);}return enumerableOf([observableFromArray(args,scheduler),this]).concat();}; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */observableProto.takeLast = function(count){if(count < 0){throw new ArgumentOutOfRangeError();}var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length > count && q.shift();},function(e){o.onError(e);},function(){while(q.length > 0) {o.onNext(q.shift());}o.onCompleted();});},source);};observableProto.flatMapConcat = observableProto.concatMap = function(selector,resultSelector,thisArg){return new FlatMapObservable(this,selector,resultSelector,thisArg).merge(1);};var MapObservable=(function(__super__){inherits(MapObservable,__super__);function MapObservable(source,selector,thisArg){this.source = source;this.selector = bindCallback(selector,thisArg,3);__super__.call(this);}function innerMap(selector,self){return function(x,i,o){return selector.call(this,self.selector(x,i,o),i,o);};}MapObservable.prototype.internalMap = function(selector,thisArg){return new MapObservable(this.source,innerMap(selector,this),thisArg);};MapObservable.prototype.subscribeCore = function(o){return this.source.subscribe(new InnerObserver(o,this.selector,this));};function InnerObserver(o,selector,source){this.o = o;this.selector = selector;this.source = source;this.i = 0;this.isStopped = false;}InnerObserver.prototype.onNext = function(x){if(this.isStopped){return;}var result=tryCatch(this.selector)(x,this.i++,this.source);if(result === errorObj){return this.o.onError(result.e);}this.o.onNext(result);};InnerObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.o.onCompleted();}};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);return true;}return false;};return MapObservable;})(ObservableBase); /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */observableProto.map = observableProto.select = function(selector,thisArg){var selectorFn=typeof selector === 'function'?selector:function(){return selector;};return this instanceof MapObservable?this.internalMap(selectorFn,thisArg):new MapObservable(this,selectorFn,thisArg);};function plucker(args,len){return function mapper(x){var currentProp=x;for(var i=0;i < len;i++) {var p=currentProp[args[i]];if(typeof p !== 'undefined'){currentProp = p;}else {return undefined;}}return currentProp;};} /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */observableProto.pluck = function(){var len=arguments.length,args=new Array(len);if(len === 0){throw new Error('List of properties cannot be empty.');}for(var i=0;i < len;i++) {args[i] = arguments[i];}return this.map(plucker(args,len));};observableProto.flatMap = observableProto.selectMany = function(selector,resultSelector,thisArg){return new FlatMapObservable(this,selector,resultSelector,thisArg).mergeAll();};Rx.Observable.prototype.flatMapWithMaxConcurrent = function(limit,selector,resultSelector,thisArg){return new FlatMapObservable(this,selector,resultSelector,thisArg).merge(limit);};Rx.Observable.prototype.flatMapLatest = function(selector,resultSelector,thisArg){return new FlatMapObservable(this,selector,resultSelector,thisArg).switchLatest();};var SkipObservable=(function(__super__){inherits(SkipObservable,__super__);function SkipObservable(source,count){this.source = source;this.skipCount = count;__super__.call(this);}SkipObservable.prototype.subscribeCore = function(o){return this.source.subscribe(new InnerObserver(o,this.skipCount));};function InnerObserver(o,c){this.c = c;this.r = c;this.o = o;this.isStopped = false;}InnerObserver.prototype.onNext = function(x){if(this.isStopped){return;}if(this.r <= 0){this.o.onNext(x);}else {this.r--;}};InnerObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.o.onCompleted();}};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);return true;}return false;};return SkipObservable;})(ObservableBase); /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */observableProto.skip = function(count){if(count < 0){throw new ArgumentOutOfRangeError();}return new SkipObservable(this,count);}; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */observableProto.skipWhile = function(predicate,thisArg){var source=this,callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0,running=false;return source.subscribe(function(x){if(!running){try{running = !callback(x,i++,source);}catch(e) {o.onError(e);return;}}running && o.onNext(x);},function(e){o.onError(e);},function(){o.onCompleted();});},source);}; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */observableProto.take = function(count,scheduler){if(count < 0){throw new ArgumentOutOfRangeError();}if(count === 0){return observableEmpty(scheduler);}var source=this;return new AnonymousObservable(function(o){var remaining=count;return source.subscribe(function(x){if(remaining-- > 0){o.onNext(x);remaining <= 0 && o.onCompleted();}},function(e){o.onError(e);},function(){o.onCompleted();});},source);}; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */observableProto.takeWhile = function(predicate,thisArg){var source=this,callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0,running=true;return source.subscribe(function(x){if(running){try{running = callback(x,i++,source);}catch(e) {o.onError(e);return;}if(running){o.onNext(x);}else {o.onCompleted();}}},function(e){o.onError(e);},function(){o.onCompleted();});},source);};var FilterObservable=(function(__super__){inherits(FilterObservable,__super__);function FilterObservable(source,predicate,thisArg){this.source = source;this.predicate = bindCallback(predicate,thisArg,3);__super__.call(this);}FilterObservable.prototype.subscribeCore = function(o){return this.source.subscribe(new InnerObserver(o,this.predicate,this));};function innerPredicate(predicate,self){return function(x,i,o){return self.predicate(x,i,o) && predicate.call(this,x,i,o);};}FilterObservable.prototype.internalFilter = function(predicate,thisArg){return new FilterObservable(this.source,innerPredicate(predicate,this),thisArg);};function InnerObserver(o,predicate,source){this.o = o;this.predicate = predicate;this.source = source;this.i = 0;this.isStopped = false;}InnerObserver.prototype.onNext = function(x){if(this.isStopped){return;}var shouldYield=tryCatch(this.predicate)(x,this.i++,this.source);if(shouldYield === errorObj){return this.o.onError(shouldYield.e);}shouldYield && this.o.onNext(x);};InnerObserver.prototype.onError = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);}};InnerObserver.prototype.onCompleted = function(){if(!this.isStopped){this.isStopped = true;this.o.onCompleted();}};InnerObserver.prototype.dispose = function(){this.isStopped = true;};InnerObserver.prototype.fail = function(e){if(!this.isStopped){this.isStopped = true;this.o.onError(e);return true;}return false;};return FilterObservable;})(ObservableBase); /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */observableProto.filter = observableProto.where = function(predicate,thisArg){return this instanceof FilterObservable?this.internalFilter(predicate,thisArg):new FilterObservable(this,predicate,thisArg);};function createCbObservable(fn,ctx,selector,args){var o=new AsyncSubject();args.push(createCbHandler(o,ctx,selector));fn.apply(ctx,args);return o.asObservable();}function createCbHandler(o,ctx,selector){return function handler(){var len=arguments.length,results=new Array(len);for(var i=0;i < len;i++) {results[i] = arguments[i];}if(isFunction(selector)){results = tryCatch(selector).apply(ctx,results);if(results === errorObj){return o.onError(results.e);}o.onNext(results);}else {if(results.length <= 1){o.onNext(results[0]);}else {o.onNext(results);}}o.onCompleted();};} /** * Converts a callback function to an observable sequence. * * @param {Function} fn Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */Observable.fromCallback = function(fn,ctx,selector){return function(){typeof ctx === 'undefined' && (ctx = this);var len=arguments.length,args=new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}return createCbObservable(fn,ctx,selector,args);};};function createNodeObservable(fn,ctx,selector,args){var o=new AsyncSubject();args.push(createNodeHandler(o,ctx,selector));fn.apply(ctx,args);return o.asObservable();}function createNodeHandler(o,ctx,selector){return function handler(){var err=arguments[0];if(err){return o.onError(err);}var len=arguments.length,results=[];for(var i=1;i < len;i++) {results[i - 1] = arguments[i];}if(isFunction(selector)){var results=tryCatch(selector).apply(ctx,results);if(results === errorObj){return o.onError(results.e);}o.onNext(results);}else {if(results.length <= 1){o.onNext(results[0]);}else {o.onNext(results);}}o.onCompleted();};} /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} fn The function to call * @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */Observable.fromNodeCallback = function(fn,ctx,selector){return function(){typeof ctx === 'undefined' && (ctx = this);var len=arguments.length,args=new Array(len);for(var i=0;i < len;i++) {args[i] = arguments[i];}return createNodeObservable(fn,ctx,selector,args);};};function ListenDisposable(e,n,fn){this._e = e;this._n = n;this._fn = fn;this._e.addEventListener(this._n,this._fn,false);this.isDisposed = false;}ListenDisposable.prototype.dispose = function(){if(!this.isDisposed){this._e.removeEventListener(this._n,this._fn,false);this.isDisposed = true;}};function createEventListener(el,eventName,handler){ // Asume NodeList or HTMLCollection var elemToString=Object.prototype.toString.call(el);if(elemToString === '[object NodeList]' || elemToString === '[object HTMLCollection]'){var disposables=new CompositeDisposable();for(var i=0,len=el.length;i < len;i++) {disposables.add(createEventListener(el.item(i),eventName,handler));}return disposables;}return new ListenDisposable(el,eventName,handler);}function eventHandler(o,selector){return function handler(){var results=arguments[0];if(isFunction(selector)){results = selector.apply(null,arguments);}o.onNext(results);};} /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */Observable.fromEvent = function(element,eventName,selector){ // Node.js specific if(element.addListener){return fromEventPattern(function(h){element.addListener(eventName,h);},function(h){element.removeListener(eventName,h);},selector);}return new AnonymousObservable(function(o){return createEventListener(element,eventName,eventHandler(o,selector));});}; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @param {Scheduler} [scheduler] A scheduler used to schedule the remove handler. * @returns {Observable} An observable sequence which wraps an event from an event emitter */var fromEventPattern=Observable.fromEventPattern = function(addHandler,removeHandler,selector,scheduler){isScheduler(scheduler) || (scheduler = immediateScheduler);return new AnonymousObservable(function(o){function innerHandler(){var result=arguments[0];if(isFunction(selector)){result = tryCatch(selector).apply(null,arguments);if(result === errorObj){return o.onError(result.e);}}o.onNext(result);}var returnValue=addHandler(innerHandler);return disposableCreate(function(){isFunction(removeHandler) && removeHandler(innerHandler,returnValue);});}).publish().refCount();};var FromPromiseObservable=(function(__super__){inherits(FromPromiseObservable,__super__);function FromPromiseObservable(p){this.p = p;__super__.call(this);}FromPromiseObservable.prototype.subscribeCore = function(o){this.p.then(function(data){o.onNext(data);o.onCompleted();},function(err){o.onError(err);});return disposableEmpty;};return FromPromiseObservable;})(ObservableBase); /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */var observableFromPromise=Observable.fromPromise = function(promise){return new FromPromiseObservable(promise);}; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */observableProto.toPromise = function(promiseCtor){promiseCtor || (promiseCtor = Rx.config.Promise);if(!promiseCtor){throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise');}var source=this;return new promiseCtor(function(resolve,reject){ // No cancellation can be done var value,hasValue=false;source.subscribe(function(v){value = v;hasValue = true;},reject,function(){hasValue && resolve(value);});});}; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */Observable.startAsync = function(functionAsync){var promise;try{promise = functionAsync();}catch(e) {return observableThrow(e);}return observableFromPromise(promise);}; /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */observableProto.multicast = function(subjectOrSubjectSelector,selector){var source=this;return typeof subjectOrSubjectSelector === 'function'?new AnonymousObservable(function(observer){var connectable=source.multicast(subjectOrSubjectSelector());return new CompositeDisposable(selector(connectable).subscribe(observer),connectable.connect());},source):new ConnectableObservable(source,subjectOrSubjectSelector);}; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */observableProto.publish = function(selector){return selector && isFunction(selector)?this.multicast(function(){return new Subject();},selector):this.multicast(new Subject());}; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */observableProto.share = function(){return this.publish().refCount();}; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */observableProto.publishLast = function(selector){return selector && isFunction(selector)?this.multicast(function(){return new AsyncSubject();},selector):this.multicast(new AsyncSubject());}; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */observableProto.publishValue = function(initialValueOrSelector,initialValue){return arguments.length === 2?this.multicast(function(){return new BehaviorSubject(initialValue);},initialValueOrSelector):this.multicast(new BehaviorSubject(initialValueOrSelector));}; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */observableProto.shareValue = function(initialValue){return this.publishValue(initialValue).refCount();}; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param windowSize [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */observableProto.replay = function(selector,bufferSize,windowSize,scheduler){return selector && isFunction(selector)?this.multicast(function(){return new ReplaySubject(bufferSize,windowSize,scheduler);},selector):this.multicast(new ReplaySubject(bufferSize,windowSize,scheduler));}; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */observableProto.shareReplay = function(bufferSize,windowSize,scheduler){return this.replay(null,bufferSize,windowSize,scheduler).refCount();};var ConnectableObservable=Rx.ConnectableObservable = (function(__super__){inherits(ConnectableObservable,__super__);function ConnectableObservable(source,subject){var hasSubscription=false,subscription,sourceObservable=source.asObservable();this.connect = function(){if(!hasSubscription){hasSubscription = true;subscription = new CompositeDisposable(sourceObservable.subscribe(subject),disposableCreate(function(){hasSubscription = false;}));}return subscription;};__super__.call(this,function(o){return subject.subscribe(o);});}ConnectableObservable.prototype.refCount = function(){var connectableSubscription,count=0,source=this;return new AnonymousObservable(function(observer){var shouldConnect=++count === 1,subscription=source.subscribe(observer);shouldConnect && (connectableSubscription = source.connect());return function(){subscription.dispose();--count === 0 && connectableSubscription.dispose();};});};return ConnectableObservable;})(Observable);function observableTimerDate(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithAbsolute(dueTime,function(){observer.onNext(0);observer.onCompleted();});});}function observableTimerDateAndPeriod(dueTime,period,scheduler){return new AnonymousObservable(function(observer){var d=dueTime,p=normalizeTime(period);return scheduler.scheduleRecursiveWithAbsoluteAndState(0,d,function(count,self){if(p > 0){var now=scheduler.now();d = d + p;d <= now && (d = now + p);}observer.onNext(count);self(count + 1,d);});});}function observableTimerTimeSpan(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithRelative(normalizeTime(dueTime),function(){observer.onNext(0);observer.onCompleted();});});}function observableTimerTimeSpanAndPeriod(dueTime,period,scheduler){return dueTime === period?new AnonymousObservable(function(observer){return scheduler.schedulePeriodicWithState(0,period,function(count){observer.onNext(count);return count + 1;});}):observableDefer(function(){return observableTimerDateAndPeriod(scheduler.now() + dueTime,period,scheduler);});} /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */var observableinterval=Observable.interval = function(period,scheduler){return observableTimerTimeSpanAndPeriod(period,period,isScheduler(scheduler)?scheduler:timeoutScheduler);}; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */var observableTimer=Observable.timer = function(dueTime,periodOrScheduler,scheduler){var period;isScheduler(scheduler) || (scheduler = timeoutScheduler);if(periodOrScheduler != null && typeof periodOrScheduler === 'number'){period = periodOrScheduler;}else if(isScheduler(periodOrScheduler)){scheduler = periodOrScheduler;}if(dueTime instanceof Date && period === undefined){return observableTimerDate(dueTime.getTime(),scheduler);}if(dueTime instanceof Date && period !== undefined){return observableTimerDateAndPeriod(dueTime.getTime(),periodOrScheduler,scheduler);}return period === undefined?observableTimerTimeSpan(dueTime,scheduler):observableTimerTimeSpanAndPeriod(dueTime,period,scheduler);};function observableDelayTimeSpan(source,dueTime,scheduler){return new AnonymousObservable(function(observer){var active=false,cancelable=new SerialDisposable(),exception=null,q=[],running=false,subscription;subscription = source.materialize().timestamp(scheduler).subscribe(function(notification){var d,shouldRun;if(notification.value.kind === 'E'){q = [];q.push(notification);exception = notification.value.exception;shouldRun = !running;}else {q.push({value:notification.value,timestamp:notification.timestamp + dueTime});shouldRun = !active;active = true;}if(shouldRun){if(exception !== null){observer.onError(exception);}else {d = new SingleAssignmentDisposable();cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime,function(self){var e,recurseDueTime,result,shouldRecurse;if(exception !== null){return;}running = true;do {result = null;if(q.length > 0 && q[0].timestamp - scheduler.now() <= 0){result = q.shift().value;}if(result !== null){result.accept(observer);}}while(result !== null);shouldRecurse = false;recurseDueTime = 0;if(q.length > 0){shouldRecurse = true;recurseDueTime = Math.max(0,q[0].timestamp - scheduler.now());}else {active = false;}e = exception;running = false;if(e !== null){observer.onError(e);}else if(shouldRecurse){self(recurseDueTime);}}));}}});return new CompositeDisposable(subscription,cancelable);},source);}function observableDelayDate(source,dueTime,scheduler){return observableDefer(function(){return observableDelayTimeSpan(source,dueTime - scheduler.now(),scheduler);});} /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */observableProto.delay = function(dueTime,scheduler){isScheduler(scheduler) || (scheduler = timeoutScheduler);return dueTime instanceof Date?observableDelayDate(this,dueTime.getTime(),scheduler):observableDelayTimeSpan(this,dueTime,scheduler);}; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */observableProto.debounce = function(dueTime,scheduler){isScheduler(scheduler) || (scheduler = timeoutScheduler);var source=this;return new AnonymousObservable(function(observer){var cancelable=new SerialDisposable(),hasvalue=false,value,id=0;var subscription=source.subscribe(function(x){hasvalue = true;value = x;id++;var currentId=id,d=new SingleAssignmentDisposable();cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleWithRelative(dueTime,function(){hasvalue && id === currentId && observer.onNext(value);hasvalue = false;}));},function(e){cancelable.dispose();observer.onError(e);hasvalue = false;id++;},function(){cancelable.dispose();hasvalue && observer.onNext(value);observer.onCompleted();hasvalue = false;id++;});return new CompositeDisposable(subscription,cancelable);},this);}; /** * @deprecated use #debounce or #throttleWithTimeout instead. */observableProto.throttle = function(dueTime,scheduler){ //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime,scheduler);}; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.default); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */observableProto.timestamp = function(scheduler){isScheduler(scheduler) || (scheduler = timeoutScheduler);return this.map(function(x){return {value:x,timestamp:scheduler.now()};});};function sampleObservable(source,sampler){return new AnonymousObservable(function(o){var atEnd=false,value,hasValue=false;function sampleSubscribe(){if(hasValue){hasValue = false;o.onNext(value);}atEnd && o.onCompleted();}var sourceSubscription=new SingleAssignmentDisposable();sourceSubscription.setDisposable(source.subscribe(function(newValue){hasValue = true;value = newValue;},function(e){o.onError(e);},function(){atEnd = true;sourceSubscription.dispose();}));return new CompositeDisposable(sourceSubscription,sampler.subscribe(sampleSubscribe,function(e){o.onError(e);},sampleSubscribe));},source);} /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */observableProto.sample = observableProto.throttleLatest = function(intervalOrSampler,scheduler){isScheduler(scheduler) || (scheduler = timeoutScheduler);return typeof intervalOrSampler === 'number'?sampleObservable(this,observableinterval(intervalOrSampler,scheduler)):sampleObservable(this,intervalOrSampler);}; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */observableProto.timeout = function(dueTime,other,scheduler){(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));isScheduler(scheduler) || (scheduler = timeoutScheduler);var source=this,schedulerMethod=dueTime instanceof Date?'scheduleWithAbsolute':'scheduleWithRelative';return new AnonymousObservable(function(observer){var id=0,original=new SingleAssignmentDisposable(),subscription=new SerialDisposable(),switched=false,timer=new SerialDisposable();subscription.setDisposable(original);function createTimer(){var myId=id;timer.setDisposable(scheduler[schedulerMethod](dueTime,function(){if(id === myId){isPromise(other) && (other = observableFromPromise(other));subscription.setDisposable(other.subscribe(observer));}}));}createTimer();original.setDisposable(source.subscribe(function(x){if(!switched){id++;observer.onNext(x);createTimer();}},function(e){if(!switched){id++;observer.onError(e);}},function(){if(!switched){id++;observer.onCompleted();}}));return new CompositeDisposable(subscription,timer);},source);}; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */observableProto.throttleFirst = function(windowDuration,scheduler){isScheduler(scheduler) || (scheduler = timeoutScheduler);var duration=+windowDuration || 0;if(duration <= 0){throw new RangeError('windowDuration cannot be less or equal zero.');}var source=this;return new AnonymousObservable(function(o){var lastOnNext=0;return source.subscribe(function(x){var now=scheduler.now();if(lastOnNext === 0 || now - lastOnNext >= duration){lastOnNext = now;o.onNext(x);}},function(e){o.onError(e);},function(){o.onCompleted();});},source);};var PausableObservable=(function(__super__){inherits(PausableObservable,__super__);function subscribe(observer){var conn=this.source.publish(),subscription=conn.subscribe(observer),connection=disposableEmpty;var pausable=this.pauser.distinctUntilChanged().subscribe(function(b){if(b){connection = conn.connect();}else {connection.dispose();connection = disposableEmpty;}});return new CompositeDisposable(subscription,connection,pausable);}function PausableObservable(source,pauser){this.source = source;this.controller = new Subject();if(pauser && pauser.subscribe){this.pauser = this.controller.merge(pauser);}else {this.pauser = this.controller;}__super__.call(this,subscribe,source);}PausableObservable.prototype.pause = function(){this.controller.onNext(false);};PausableObservable.prototype.resume = function(){this.controller.onNext(true);};return PausableObservable;})(Observable); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */observableProto.pausable = function(pauser){return new PausableObservable(this,pauser);};function combineLatestSource(source,subject,resultSelector){return new AnonymousObservable(function(o){var hasValue=[false,false],hasValueAll=false,isDone=false,values=new Array(2),err;function next(x,i){values[i] = x;hasValue[i] = true;if(hasValueAll || (hasValueAll = hasValue.every(identity))){if(err){return o.onError(err);}var res=tryCatch(resultSelector).apply(null,values);if(res === errorObj){return o.onError(res.e);}o.onNext(res);}isDone && values[1] && o.onCompleted();}return new CompositeDisposable(source.subscribe(function(x){next(x,0);},function(e){if(values[1]){o.onError(e);}else {err = e;}},function(){isDone = true;values[1] && o.onCompleted();}),subject.subscribe(function(x){next(x,1);},function(e){o.onError(e);},function(){isDone = true;next(true,1);}));},source);}var PausableBufferedObservable=(function(__super__){inherits(PausableBufferedObservable,__super__);function subscribe(o){var q=[],previousShouldFire;function drainQueue(){while(q.length > 0) {o.onNext(q.shift());}}var subscription=combineLatestSource(this.source,this.pauser.startWith(false).distinctUntilChanged(),function(data,shouldFire){return {data:data,shouldFire:shouldFire};}).subscribe(function(results){if(previousShouldFire !== undefined && results.shouldFire != previousShouldFire){previousShouldFire = results.shouldFire; // change in shouldFire if(results.shouldFire){drainQueue();}}else {previousShouldFire = results.shouldFire; // new data if(results.shouldFire){o.onNext(results.data);}else {q.push(results.data);}}},function(err){drainQueue();o.onError(err);},function(){drainQueue();o.onCompleted();});return subscription;}function PausableBufferedObservable(source,pauser){this.source = source;this.controller = new Subject();if(pauser && pauser.subscribe){this.pauser = this.controller.merge(pauser);}else {this.pauser = this.controller;}__super__.call(this,subscribe,source);}PausableBufferedObservable.prototype.pause = function(){this.controller.onNext(false);};PausableBufferedObservable.prototype.resume = function(){this.controller.onNext(true);};return PausableBufferedObservable;})(Observable); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */observableProto.pausableBuffered = function(subject){return new PausableBufferedObservable(this,subject);};var ControlledObservable=(function(__super__){inherits(ControlledObservable,__super__);function subscribe(observer){return this.source.subscribe(observer);}function ControlledObservable(source,enableQueue,scheduler){__super__.call(this,subscribe,source);this.subject = new ControlledSubject(enableQueue,scheduler);this.source = source.multicast(this.subject).refCount();}ControlledObservable.prototype.request = function(numberOfItems){return this.subject.request(numberOfItems == null?-1:numberOfItems);};return ControlledObservable;})(Observable);var ControlledSubject=(function(__super__){function subscribe(observer){return this.subject.subscribe(observer);}inherits(ControlledSubject,__super__);function ControlledSubject(enableQueue,scheduler){enableQueue == null && (enableQueue = true);__super__.call(this,subscribe);this.subject = new Subject();this.enableQueue = enableQueue;this.queue = enableQueue?[]:null;this.requestedCount = 0;this.requestedDisposable = null;this.error = null;this.hasFailed = false;this.hasCompleted = false;this.scheduler = scheduler || currentThreadScheduler;}addProperties(ControlledSubject.prototype,Observer,{onCompleted:function onCompleted(){this.hasCompleted = true;if(!this.enableQueue || this.queue.length === 0){this.subject.onCompleted();this.disposeCurrentRequest();}else {this.queue.push(Notification.createOnCompleted());}},onError:function onError(error){this.hasFailed = true;this.error = error;if(!this.enableQueue || this.queue.length === 0){this.subject.onError(error);this.disposeCurrentRequest();}else {this.queue.push(Notification.createOnError(error));}},onNext:function onNext(value){if(this.requestedCount <= 0){this.enableQueue && this.queue.push(Notification.createOnNext(value));}else {this.requestedCount-- === 0 && this.disposeCurrentRequest();this.subject.onNext(value);}},_processRequest:function _processRequest(numberOfItems){if(this.enableQueue){while(this.queue.length > 0 && (numberOfItems > 0 || this.queue[0].kind !== 'N')) {var first=this.queue.shift();first.accept(this.subject);if(first.kind === 'N'){numberOfItems--;}else {this.disposeCurrentRequest();this.queue = [];}}}return numberOfItems;},request:function request(number){this.disposeCurrentRequest();var self=this;this.requestedDisposable = this.scheduler.scheduleWithState(number,function(s,i){var remaining=self._processRequest(i);var stopped=self.hasCompleted || self.hasFailed;if(!stopped && remaining > 0){self.requestedCount = remaining;return disposableCreate(function(){self.requestedCount = 0;}); // Scheduled item is still in progress. Return a new // disposable to allow the request to be interrupted // via dispose. }});return this.requestedDisposable;},disposeCurrentRequest:function disposeCurrentRequest(){if(this.requestedDisposable){this.requestedDisposable.dispose();this.requestedDisposable = null;}}});return ControlledSubject;})(Observable); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request * @param {Scheduler} scheduler determines how the requests will be scheduled * @returns {Observable} The observable sequence which only propagates values on request. */observableProto.controlled = function(enableQueue,scheduler){if(enableQueue && isScheduler(enableQueue)){scheduler = enableQueue;enableQueue = true;}if(enableQueue == null){enableQueue = true;}return new ControlledObservable(this,enableQueue,scheduler);}; /** * Pipes the existing Observable sequence into a Node.js Stream. * @param {Stream} dest The destination Node.js stream. * @returns {Stream} The destination stream. */observableProto.pipe = function(dest){var source=this.pausableBuffered();function onDrain(){source.resume();}dest.addListener('drain',onDrain);source.subscribe(function(x){!dest.write(String(x)) && source.pause();},function(err){dest.emit('error',err);},function(){ // Hack check because STDIO is not closable !dest._isStdio && dest.end();dest.removeListener('drain',onDrain);});source.resume();return dest;};var AnonymousObservable=Rx.AnonymousObservable = (function(__super__){inherits(AnonymousObservable,__super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber){return subscriber && isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty;}function setDisposable(s,state){var ado=state[0],self=state[1];var sub=tryCatch(self.__subscribe).call(self,ado);if(sub === errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e);}}ado.setDisposable(fixSubscriber(sub));}function innerSubscribe(observer){var ado=new AutoDetachObserver(observer),state=[ado,this];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable);}else {setDisposable(null,state);}return ado;}function AnonymousObservable(subscribe,parent){this.source = parent;this.__subscribe = subscribe;__super__.call(this,innerSubscribe);}return AnonymousObservable;})(Observable);var AutoDetachObserver=(function(__super__){inherits(AutoDetachObserver,__super__);function AutoDetachObserver(observer){__super__.call(this);this.observer = observer;this.m = new SingleAssignmentDisposable();}var AutoDetachObserverPrototype=AutoDetachObserver.prototype;AutoDetachObserverPrototype.next = function(value){var result=tryCatch(this.observer.onNext).call(this.observer,value);if(result === errorObj){this.dispose();thrower(result.e);}};AutoDetachObserverPrototype.error = function(err){var result=tryCatch(this.observer.onError).call(this.observer,err);this.dispose();result === errorObj && thrower(result.e);};AutoDetachObserverPrototype.completed = function(){var result=tryCatch(this.observer.onCompleted).call(this.observer);this.dispose();result === errorObj && thrower(result.e);};AutoDetachObserverPrototype.setDisposable = function(value){this.m.setDisposable(value);};AutoDetachObserverPrototype.getDisposable = function(){return this.m.getDisposable();};AutoDetachObserverPrototype.dispose = function(){__super__.prototype.dispose.call(this);this.m.dispose();};return AutoDetachObserver;})(AbstractObserver);var InnerSubscription=function InnerSubscription(subject,observer){this.subject = subject;this.observer = observer;};InnerSubscription.prototype.dispose = function(){if(!this.subject.isDisposed && this.observer !== null){var idx=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(idx,1);this.observer = null;}}; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */var Subject=Rx.Subject = (function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer);}if(this.hasError){observer.onError(this.error);return disposableEmpty;}observer.onCompleted();return disposableEmpty;}inherits(Subject,__super__); /** * Creates a subject. */function Subject(){__super__.call(this,subscribe);this.isDisposed = false,this.isStopped = false,this.observers = [];this.hasError = false;}addProperties(Subject.prototype,Observer.prototype,{ /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */hasObservers:function hasObservers(){return this.observers.length > 0;}, /** * Notifies all subscribed observers about the end of the sequence. */onCompleted:function onCompleted(){checkDisposed(this);if(!this.isStopped){this.isStopped = true;for(var i=0,os=cloneArray(this.observers),len=os.length;i < len;i++) {os[i].onCompleted();}this.observers.length = 0;}}, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */onError:function onError(error){checkDisposed(this);if(!this.isStopped){this.isStopped = true;this.error = error;this.hasError = true;for(var i=0,os=cloneArray(this.observers),len=os.length;i < len;i++) {os[i].onError(error);}this.observers.length = 0;}}, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */onNext:function onNext(value){checkDisposed(this);if(!this.isStopped){for(var i=0,os=cloneArray(this.observers),len=os.length;i < len;i++) {os[i].onNext(value);}}}, /** * Unsubscribe all observers and release resources. */dispose:function dispose(){this.isDisposed = true;this.observers = null;}}); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */Subject.create = function(observer,observable){return new AnonymousSubject(observer,observable);};return Subject;})(Observable); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */var AsyncSubject=Rx.AsyncSubject = (function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer);}if(this.hasError){observer.onError(this.error);}else if(this.hasValue){observer.onNext(this.value);observer.onCompleted();}else {observer.onCompleted();}return disposableEmpty;}inherits(AsyncSubject,__super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */function AsyncSubject(){__super__.call(this,subscribe);this.isDisposed = false;this.isStopped = false;this.hasValue = false;this.observers = [];this.hasError = false;}addProperties(AsyncSubject.prototype,Observer,{ /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */hasObservers:function hasObservers(){checkDisposed(this);return this.observers.length > 0;}, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */onCompleted:function onCompleted(){var i,len;checkDisposed(this);if(!this.isStopped){this.isStopped = true;var os=cloneArray(this.observers),len=os.length;if(this.hasValue){for(i = 0;i < len;i++) {var o=os[i];o.onNext(this.value);o.onCompleted();}}else {for(i = 0;i < len;i++) {os[i].onCompleted();}}this.observers.length = 0;}}, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */onError:function onError(error){checkDisposed(this);if(!this.isStopped){this.isStopped = true;this.hasError = true;this.error = error;for(var i=0,os=cloneArray(this.observers),len=os.length;i < len;i++) {os[i].onError(error);}this.observers.length = 0;}}, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */onNext:function onNext(value){checkDisposed(this);if(this.isStopped){return;}this.value = value;this.hasValue = true;}, /** * Unsubscribe all observers and release resources. */dispose:function dispose(){this.isDisposed = true;this.observers = null;this.exception = null;this.value = null;}});return AsyncSubject;})(Observable);var AnonymousSubject=Rx.AnonymousSubject = (function(__super__){inherits(AnonymousSubject,__super__);function subscribe(observer){return this.observable.subscribe(observer);}function AnonymousSubject(observer,observable){this.observer = observer;this.observable = observable;__super__.call(this,subscribe);}addProperties(AnonymousSubject.prototype,Observer.prototype,{onCompleted:function onCompleted(){this.observer.onCompleted();},onError:function onError(error){this.observer.onError(error);},onNext:function onNext(value){this.observer.onNext(value);}});return AnonymousSubject;})(Observable); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */var BehaviorSubject=Rx.BehaviorSubject = (function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);observer.onNext(this.value);return new InnerSubscription(this,observer);}if(this.hasError){observer.onError(this.error);}else {observer.onCompleted();}return disposableEmpty;}inherits(BehaviorSubject,__super__); /** * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */function BehaviorSubject(value){__super__.call(this,subscribe);this.value = value,this.observers = [],this.isDisposed = false,this.isStopped = false,this.hasError = false;}addProperties(BehaviorSubject.prototype,Observer,{ /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */getValue:function getValue(){checkDisposed(this);if(this.hasError){throw this.error;}return this.value;}, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */hasObservers:function hasObservers(){return this.observers.length > 0;}, /** * Notifies all subscribed observers about the end of the sequence. */onCompleted:function onCompleted(){checkDisposed(this);if(this.isStopped){return;}this.isStopped = true;for(var i=0,os=cloneArray(this.observers),len=os.length;i < len;i++) {os[i].onCompleted();}this.observers.length = 0;}, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */onError:function onError(error){checkDisposed(this);if(this.isStopped){return;}this.isStopped = true;this.hasError = true;this.error = error;for(var i=0,os=cloneArray(this.observers),len=os.length;i < len;i++) {os[i].onError(error);}this.observers.length = 0;}, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */onNext:function onNext(value){checkDisposed(this);if(this.isStopped){return;}this.value = value;for(var i=0,os=cloneArray(this.observers),len=os.length;i < len;i++) {os[i].onNext(value);}}, /** * Unsubscribe all observers and release resources. */dispose:function dispose(){this.isDisposed = true;this.observers = null;this.value = null;this.exception = null;}});return BehaviorSubject;})(Observable); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */var ReplaySubject=Rx.ReplaySubject = (function(__super__){var maxSafeInteger=Math.pow(2,53) - 1;function createRemovableDisposable(subject,observer){return disposableCreate(function(){observer.dispose();!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer),1);});}function subscribe(observer){var so=new ScheduledObserver(this.scheduler,observer),subscription=createRemovableDisposable(this,so);checkDisposed(this);this._trim(this.scheduler.now());this.observers.push(so);for(var i=0,len=this.q.length;i < len;i++) {so.onNext(this.q[i].value);}if(this.hasError){so.onError(this.error);}else if(this.isStopped){so.onCompleted();}so.ensureActive();return subscription;}inherits(ReplaySubject,__super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */function ReplaySubject(bufferSize,windowSize,scheduler){this.bufferSize = bufferSize == null?maxSafeInteger:bufferSize;this.windowSize = windowSize == null?maxSafeInteger:windowSize;this.scheduler = scheduler || currentThreadScheduler;this.q = [];this.observers = [];this.isStopped = false;this.isDisposed = false;this.hasError = false;this.error = null;__super__.call(this,subscribe);}addProperties(ReplaySubject.prototype,Observer.prototype,{ /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */hasObservers:function hasObservers(){return this.observers.length > 0;},_trim:function _trim(now){while(this.q.length > this.bufferSize) {this.q.shift();}while(this.q.length > 0 && now - this.q[0].interval > this.windowSize) {this.q.shift();}}, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */onNext:function onNext(value){checkDisposed(this);if(this.isStopped){return;}var now=this.scheduler.now();this.q.push({interval:now,value:value});this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i < len;i++) {var observer=os[i];observer.onNext(value);observer.ensureActive();}}, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */onError:function onError(error){checkDisposed(this);if(this.isStopped){return;}this.isStopped = true;this.error = error;this.hasError = true;var now=this.scheduler.now();this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i < len;i++) {var observer=os[i];observer.onError(error);observer.ensureActive();}this.observers.length = 0;}, /** * Notifies all subscribed observers about the end of the sequence. */onCompleted:function onCompleted(){checkDisposed(this);if(this.isStopped){return;}this.isStopped = true;var now=this.scheduler.now();this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i < len;i++) {var observer=os[i];observer.onCompleted();observer.ensureActive();}this.observers.length = 0;}, /** * Unsubscribe all observers and release resources. */dispose:function dispose(){this.isDisposed = true;this.observers = null;}});return ReplaySubject;})(Observable); /** * Used to pause and resume streams. */Rx.Pauser = (function(__super__){inherits(Pauser,__super__);function Pauser(){__super__.call(this);} /** * Pauses the underlying sequence. */Pauser.prototype.pause = function(){this.onNext(false);}; /** * Resumes the underlying sequence. */Pauser.prototype.resume = function(){this.onNext(true);};return Pauser;})(Subject);module.exports = Rx; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(15))) /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {"use strict"; var _require = __webpack_require__(3); var Observable = _require.Observable; function RequestError(url, xhr, message) { var reason = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; this.name = "RequestError"; this.url = url; this.xhr = xhr; this.code = xhr.status; this.reason = reason; this.message = "request: " + message + " (" + url + ")"; if (Error.captureStackTrace) { Error.captureStackTrace(this, RequestError); } } RequestError.prototype = new Error(); function RestCallMethodError(url, _ref) { var code = _ref.code; var method = _ref.method; var message = _ref.message; this.name = "RestCallMethodError"; this.url = url; this.code = code; this.message = "restmethodcall: webservice error status " + code + " (" + url + ")" + (method ? " (" + method + ")" : "") + (message ? "\n" + message : ""); if (Error.captureStackTrace) { Error.captureStackTrace(this, RestCallMethodError); } } RestCallMethodError.prototype = new Error(); function RestCallResult(response, url, scriptInfo) { var restCallResult = response.querySelector("RestCallResult"); var status = +restCallResult.querySelector("Status").textContent; if (status < 0) throw new RestCallMethodError(url, { code: status, method: scriptInfo });else return { output: restCallResult.querySelector("Output"), status: status }; } function toJSONForIE(blob) { try { return JSON.parse(blob); } catch (e) { return null; } } function getResponseHeadersList(xhr, headersList) { var headers = {}, header; for (var i = 0; i < headersList.length; i++) { header = headersList[i]; headers[header] = xhr.getResponseHeader(header); } return headers; } /** * Creates an observable HTTP request. * The options that can be passed are: * * - url Request's url * - [method] HTTP method (defaults is "GET") * - [data] Sent data for "POST", "UPDATE" or "PATCH" requests * - [headers] Object containing headers key/value * - [format] Format of the response, according to the XMLHttpRequest Level 2 * response type: "arraybuffer", "blob", "document", "json" or "text" (defaults) */ function request(options) { if (options.format == "rest-call-method") { return restCallMethod(options); } return Observable.create(function (observer) { var url = options.url; var method = options.method; var data = options.data; var headers = options.headers; var format = options.format; var withMetadata = options.withMetadata; var responseHeaders = options.responseHeaders; var xhr = new XMLHttpRequest(); xhr.open(method || "GET", url, true); // Special case for document format: some manifests may have a // null response because of wrongly namespaced XML file. Also the // document format rely on specific Content-Type headers which may // erroneous. Therefore we use a text responseType and parse the // document with DOMParser. if (format == "document") { xhr.responseType = "text"; } else { xhr.responseType = format || "text"; } if (headers) { for (var name in headers) xhr.setRequestHeader(name, headers[name]); } xhr.addEventListener("load", onLoad, false); xhr.addEventListener("error", onError, false); var sent = Date.now(); xhr.send(data); function onLoad(evt) { var x = evt.target; var s = x.status; if (s < 200 || s >= 300) { return observer.onError(new RequestError(url, x, x.statusText)); } var duration = Date.now() - sent; var blob; if (format == "document") { blob = new global.DOMParser().parseFromString(x.responseText, "text/xml"); } else { blob = x.response; } if (format == "json" && typeof blob == "string") { blob = toJSONForIE(blob); } if (blob == null) { return observer.onError(new RequestError(url, x, "null response with format \"" + format + "\" (error while parsing or wrong content-type)")); } // TODO(pierre): find a better API than this "withMetadata" flag // (it is weird and collisions with responseHeaders) if (withMetadata) { var headers; if (responseHeaders) { headers = getResponseHeadersList(x, responseHeaders); } var size = evt.total; observer.onNext({ blob: blob, size: size, duration: duration, headers: headers, url: x.responseURL || url, xhr: x }); } else { observer.onNext(blob); } observer.onCompleted(); } function onError(e) { observer.onError(new RequestError(url, e, "error event")); } return function () { var _xhr = xhr; var readyState = _xhr.readyState; if (0 < readyState && readyState < 4) { xhr.removeEventListener("load", onLoad); xhr.removeEventListener("error", onError); xhr.abort(); } xhr = null; }; }); } var ENTITIES_REG = /[&<>]/g; var ENTITIES = { "&": "&amp;", "<": "&lt;", ">": "&gt;" }; function escapeXml(xml) { return (xml || "").toString().replace(ENTITIES_REG, function (tag) { return ENTITIES[tag]; }); } function objToXML(obj) { var xml = ""; for (var attrName in obj) { var attr = obj[attrName]; var inner = typeof attr == "object" ? objToXML(attr) : escapeXml(attr); xml += "<" + attrName + ">" + inner + "</" + attrName + ">"; } return xml; } function getNodeTextContent(root, name) { var item = root.querySelector(name); return item && item.textContent; } var METHOD_CALL_XML = "<RestCallMethod xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">{payload}</RestCallMethod>"; function restCallMethod(options) { options.method = "POST"; options.headers = { "Content-Type": "application/xml" }; options.data = METHOD_CALL_XML.replace("{payload}", objToXML(options.data)); options.format = "document"; // options.url = options.url.replace("RestPortalProvider", "JsonPortalProvider"); // options.headers = { "Content-Type": "application/json" }; // options.data = JSON.stringify(options.data); // options.format = "json"; return request(options).map(function (data) { return RestCallResult(data, options.url, options.ScriptInfo); }); } request.escapeXml = escapeXml; request.RequestError = RequestError; request.RestCallMethodError = RestCallMethodError; request.RestCallResult = RestCallResult; request.getNodeTextContent = getNodeTextContent; module.exports = request; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 15 */ /***/ function(module, exports) { // shim for using process in browser 'use strict'; var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/'; }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function () { return 0; }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _ = __webpack_require__(1); var log = __webpack_require__(4); var Promise_ = __webpack_require__(6); var assert = __webpack_require__(2); var _require = __webpack_require__(3); var Observable = _require.Observable; var combineLatest = Observable.combineLatest; var empty = Observable.empty; var fromPromise = Observable.fromPromise; var merge = Observable.merge; var just = Observable.just; var _require2 = __webpack_require__(8); var KeySystemAccess = _require2.KeySystemAccess; var requestMediaKeySystemAccess = _require2.requestMediaKeySystemAccess; var setMediaKeys = _require2.setMediaKeys; var emeEvents = _require2.emeEvents; var onEncrypted = emeEvents.onEncrypted; var onKeyMessage = emeEvents.onKeyMessage; var onKeyError = emeEvents.onKeyError; var onKeyStatusesChange = emeEvents.onKeyStatusesChange; var SYSTEMS = { "clearkey": ["webkit-org.w3.clearkey", "org.w3.clearkey"], "widevine": ["com.widevine.alpha"], "playready": ["com.youtube.playready", "com.microsoft.playready"] }; // Key statuses to error mapping. Taken from shaka-player. var KEY_STATUS_ERRORS = { "output-not-allowed": "eme: the required output protection is not available.", "expired": "eme: a required key has expired and the content cannot be decrypted.", "internal-error": "eme: an unknown error has occurred in the CDM." }; function hashBuffer(buffer) { var hash = 0; var char = undefined; for (var i = 0; i < buffer.length; i++) { char = buffer[i]; hash = (hash << 5) - hash + char; hash = hash & hash; // Convert to 32bit integer } return hash; } function hashInitData(initData) { if (typeof initData == "number") { return initData; } else { return hashBuffer(initData); } } var NotSupportedKeySystemError = function NotSupportedKeySystemError() { return new Error("eme: could not find a compatible key system"); }; /** * Set maintaining a representation of all currently loaded * MediaKeySessions. This set allow to reuse sessions without re- * negotiating a license exchange if the key is already used in a * loaded session. */ var InMemorySessionsSet = (function () { function InMemorySessionsSet() { _classCallCheck(this, InMemorySessionsSet); this._entries = []; } /** * Set representing persisted licenses. Depends on a simple local- * storage implementation with a `save`/`load` synchronous interface * to persist informations on persisted sessions. * * This set is used only for a cdm/keysystem with license persistency * supported. */ InMemorySessionsSet.prototype.getFirst = function getFirst() { if (this._entries.length > 0) { return this._entries[0].session; } }; InMemorySessionsSet.prototype.get = function get(initData) { initData = hashInitData(initData); var entry = _.find(this._entries, function (entry) { return entry.initData === initData; }); if (entry) { return entry.session; } }; InMemorySessionsSet.prototype.add = function add(initData, session) { var _this = this; initData = hashInitData(initData); if (!this.get(initData)) { var _ret = (function () { var sessionId = session.sessionId; if (!sessionId) { return { v: undefined }; } var entry = { session: session, initData: initData }; log.debug("eme-mem-store: add session", entry); _this._entries.push(entry); session.closed.then(function () { log.debug("eme-mem-store: remove closed session", entry); var idx = _this._entries.indexOf(entry); if (idx >= 0) { _this._entries.splice(idx, 1); } }); })(); if (typeof _ret === "object") return _ret.v; } }; InMemorySessionsSet.prototype["delete"] = function _delete(sessionId) { var entry = _.find(this._entries, function (entry) { return entry.session.sessionId === sessionId; }); if (entry) { log.debug("eme-mem-store: delete session", sessionId); var idx = this._entries.indexOf(entry); this._entries.splice(idx, 1); return entry.session; } }; InMemorySessionsSet.prototype.deleteAndClose = function deleteAndClose(sessionId) { var session = this["delete"](sessionId); if (session) { log.debug("eme-mem-store: close session", sessionId); return session.close(); } else { return Promise_.resolve(); } }; InMemorySessionsSet.prototype.dispose = function dispose() { var disposed = this._entries.map(function (_ref) { var session = _ref.session; return session.close(); }); this._entires = []; return Promise_.all(disposed); }; return InMemorySessionsSet; })(); var PersistedSessionsSet = (function () { function PersistedSessionsSet(storage) { _classCallCheck(this, PersistedSessionsSet); this.setStorage(storage); } PersistedSessionsSet.prototype.setStorage = function setStorage(storage) { if (this._storage === storage) { return; } assert(storage, "eme: no licenseStorage given for keySystem with persistentLicense"); assert.iface(storage, "licenseStorage", { save: "function", load: "function" }); this._storage = storage; try { this._entries = this._storage.load(); assert(Array.isArray(this._entries)); } catch (e) { log.warn("eme-persitent-store: could not get entries from license storage", e); this.dispose(); } }; PersistedSessionsSet.prototype.get = function get(initData) { initData = hashInitData(initData); var entry = _.find(this._entries, function (entry) { return entry.initData === initData; }); if (entry) { return entry.sessionId; } }; PersistedSessionsSet.prototype.add = function add(initData, session) { initData = hashInitData(initData); if (session.sessionType == "persistent-license" && !this.get(initData)) { var sessionId = session.sessionId; if (!sessionId) { return; } log.info("eme-persitent-store: add new session", sessionId, session); this._entries.push({ sessionId: sessionId, initData: initData }); this._save(); } }; PersistedSessionsSet.prototype["delete"] = function _delete(initData) { initData = hashInitData(initData); var entry = _.find(this._entries, function (entry) { return entry.initData === initData; }); if (entry) { log.warn("eme-persitent-store: delete session from store", entry); var idx = this._entries.indexOf(entry); this._entries.splice(idx, 1); this._save(); } }; PersistedSessionsSet.prototype.dispose = function dispose() { this._entries = []; this._save(); }; PersistedSessionsSet.prototype._save = function _save() { try { this._storage.save(this._entries); } catch (e) { log.warn("eme-persitent-store: could not save licenses in localStorage"); } }; return PersistedSessionsSet; })(); var emptyStorage = { load: function load() { return []; }, save: function save() {} }; var $storedSessions = new PersistedSessionsSet(emptyStorage); var $loadedSessions = new InMemorySessionsSet(); // Persisted singleton instance of MediaKeys. We do not allow multiple // CDM instances. var $mediaKeys = undefined; var $mediaKeySystemConfiguration = undefined; var $keySystem = undefined; var $videoElement = undefined; function getCachedKeySystemAccess(keySystems) { // NOTE(pierre): alwaysRenew flag is used for IE11 which require the // creation of a new MediaKeys instance for each session creation if (!$keySystem || !$mediaKeys || $mediaKeys.alwaysRenew) { return null; } var configuration = $mediaKeySystemConfiguration; var foundKeySystem = _.find(keySystems, function (ks) { if (ks.type !== $keySystem.type) { return false; } if (ks.persistentLicense && configuration.persistentState != "required") { return false; } if (ks.distinctiveIdentifierRequired && configuration.distinctiveIdentifier != "required") { return false; } return true; }); if (foundKeySystem) { return { keySystem: foundKeySystem, keySystemAccess: new KeySystemAccess($keySystem, $mediaKeys, $mediaKeySystemConfiguration) }; } else { return null; } } function buildKeySystemConfiguration(keySystem) { var sessionTypes = ["temporary"]; var persistentState = "optional"; var distinctiveIdentifier = "optional"; if (keySystem.persistentLicense) { persistentState = "required"; sessionTypes.push("persistent-license"); } if (keySystem.persistentStateRequired) { persistentState = "required"; } if (keySystem.distinctiveIdentifierRequired) { distinctiveIdentifier = "required"; } return { videoCapabilities: undefined, audioCapabilities: undefined, initDataTypes: ["cenc"], distinctiveIdentifier: distinctiveIdentifier, persistentState: persistentState, sessionTypes: sessionTypes }; } function findCompatibleKeySystem(keySystems) { // Fast way to find a compatible keySystem if the currently loaded // one as exactly the same compatibility options. var cachedKeySystemAccess = getCachedKeySystemAccess(keySystems); if (cachedKeySystemAccess) { log.debug("eme: found compatible keySystem quickly", cachedKeySystemAccess); return just(cachedKeySystemAccess); } var keySystemsType = _.flatten(keySystems, function (keySystem) { return _.map(SYSTEMS[keySystem.type], function (keyType) { return { keyType: keyType, keySystem: keySystem }; }); }); return Observable.create(function (obs) { var disposed = false; function testKeySystem(index) { if (disposed) { return; } if (index >= keySystemsType.length) { obs.onError(NotSupportedKeySystemError()); return; } var _keySystemsType$index = keySystemsType[index]; var keyType = _keySystemsType$index.keyType; var keySystem = _keySystemsType$index.keySystem; var keySystemConfigurations = [buildKeySystemConfiguration(keySystem)]; log.debug("eme: request keysystem access " + keyType + "," + (index + 1 + " of " + keySystemsType.length), keySystemConfigurations); requestMediaKeySystemAccess(keyType, keySystemConfigurations).then(function (keySystemAccess) { log.info("eme: found compatible keysystem", keyType, keySystemConfigurations); obs.onNext({ keySystem: keySystem, keySystemAccess: keySystemAccess }); obs.onCompleted(); }, function () { log.debug("eme: rejected access to keysystem", keyType, keySystemConfigurations); testKeySystem(index + 1); }); } testKeySystem(0); (function () { return disposed = true; }); }); } function createAndSetMediaKeys(video, keySystem, keySystemAccess) { var oldVideoElement = $videoElement; var oldMediaKeys = $mediaKeys; return fromPromise(keySystemAccess.createMediaKeys().then(function (mk) { $mediaKeys = mk; $mediaKeySystemConfiguration = keySystemAccess.getConfiguration(); $keySystem = keySystem; $videoElement = video; if (video.mediaKeys === mk) { return Promise.resolve(mk); } if (oldMediaKeys && oldMediaKeys !== $mediaKeys) { // if we change our mediaKeys singleton, we need to dispose all existing // sessions linked to the previous one. $loadedSessions.dispose(); } if (oldVideoElement && oldVideoElement !== $videoElement) { log.debug("eme: unlink old video element and set mediakeys"); return setMediaKeys(oldVideoElement, null).then(function () { return setMediaKeys($videoElement, mk); }).then(function () { return mk; }); } else { log.debug("eme: set mediakeys"); return setMediaKeys($videoElement, mk).then(function () { return mk; }); } })); } function createSession(mediaKeys, sessionType) { var session = mediaKeys.createSession(sessionType); session.sessionType = sessionType; return session; } function makeNewKeyRequest(session, initDataType, initData) { log.debug("eme: generate request", initDataType, initData); return fromPromise(session.generateRequest(initDataType, initData).then(function () { return session; })); } function loadPersistedSession(session, sessionId) { log.debug("eme: load persisted session", sessionId); return fromPromise(session.load(sessionId).then(function (success) { return { success: success, session: session }; })); } function logAndThrow(errMessage, reason) { var error = new Error(errMessage); if (reason) { error.reason = reason; } log.error(errMessage, reason); throw error; } function toObservable(value) { if (_.isPromise(value)) return fromPromise(value); if (!_.isObservable(value)) return just(value); return value; } /** * EME abstraction and event handler used to communicate with the Content- * Description-Module (CDM). * * The communication with backend key-servers is not handled directly by this * module but through the given "KeySystems". * * A system has to expose the given interface: * interface KeySystem { * readonly attribute string type; * * Promise<AB> getLicense((AB) challenge); * AB extractInitData(AB); * } * with AB = ArrayBuffer or ArrayBufferView * * The `extraInitData` method is not mandatory and used to pre-process the * initData vector injected into the CDM. The `getLicense` method is used to * serve the license encapsulated in a promise to support asynchronous license * fetching. The challenge buffer sent by the CDM is directly passed as first * argument of this method. * * The EME handler can be given one or multiple systems and will choose the * appropriate one supported by the user's browser. */ function EME(video, keySystems) { if (false) { _.each(keySystems, function (ks) { return assert.iface(ks, "keySystem", { getLicense: "function", type: "string" }); }); } function handleEncryptedEvents(encryptedEvent, _ref2) { var keySystem = _ref2.keySystem; var keySystemAccess = _ref2.keySystemAccess; if (keySystem.persistentLicense) { $storedSessions.setStorage(keySystem.licenseStorage); } var initData = new Uint8Array(encryptedEvent.initData); var initDataType = encryptedEvent.initDataType; var mediaKeySystemConfiguration = keySystemAccess.getConfiguration(); log.info("eme: encrypted event", encryptedEvent); return createAndSetMediaKeys(video, keySystem, keySystemAccess).flatMap(function (mediaKeys) { return manageSessionCreation(mediaKeys, mediaKeySystemConfiguration, keySystem, initDataType, initData).tap(function (session) { $storedSessions.add(initData, session); $loadedSessions.add(initData, session); }, function (error) { log.error("eme: error during session management handler", error); }); }).flatMap(function (session) { return handleMessageEvents(session, keySystem).tapOnError(function (error) { log.error("eme: error in session messages handler", session, error); $storedSessions["delete"](initData); $loadedSessions.deleteAndClose(session.sessionId); }); }); } function manageSessionCreation(mediaKeys, mediaKeySystemConfiguration, keySystem, initDataType, initData) { // reuse currently loaded sessions without making a new key // request var loadedSession = $loadedSessions.get(initData); if (loadedSession) { log.debug("eme: reuse loaded session", loadedSession.sessionId); return just(loadedSession); } var persistentLicenseSupported = mediaKeySystemConfiguration.sessionTypes.indexOf("persistent-license") >= 0; var sessionType = persistentLicenseSupported && keySystem.persistentLicense ? "persistent-license" : "temporary"; if (persistentLicenseSupported && keySystem.persistentLicense) { var storedSessionId = $storedSessions.get(initData); // if a persisted session exists in the store associated to this // initData, we reuse it without a new license request through // the `load` method. if (storedSessionId) { return makeNewPersistentSessionAndLoad(mediaKeys, storedSessionId, initDataType, initData); } } // we have a fresh session without persisted informations and need // to make a new key request that we will associate to this // session return makeNewSessionAndCreateKeyRequest(mediaKeys, sessionType, initDataType, initData); } function makeNewSessionAndCreateKeyRequest(mediaKeys, sessionType, initDataType, initData) { log.debug("eme: create a new " + sessionType + " session"); var session = createSession(mediaKeys, sessionType); return makeNewKeyRequest(session, initDataType, initData)["catch"](function (err) { var firstLoadedSession = $loadedSessions.getFirst(); if (!firstLoadedSession) { throw err; } log.warn("eme: could not create a new session, " + "retry after closing a currently loaded session", err); return Observable.from(firstLoadedSession.close()).flatMap(function () { return makeNewKeyRequest(createSession(mediaKeys, sessionType), initDataType, initData); }); }); } function makeNewPersistentSessionAndLoad(mediaKeys, storedSessionId, initDataType, initData) { var sessionType = "persistent-license"; log.debug("eme: create a new " + sessionType + " session"); var session = createSession(mediaKeys, sessionType); return loadPersistedSession(session, storedSessionId)["catch"](function (err) { log.warn("eme: failed to load persisted session, do fallback", storedSessionId, err); $storedSessions["delete"](initData); $loadedSessions["delete"](storedSessionId); var newSession = makeNewSessionAndCreateKeyRequest(mediaKeys, sessionType, initDataType, initData); return newSession.map(function (session) { return { success: true, session: session }; }); }).flatMap(function (_ref3) { var success = _ref3.success; var session = _ref3.session; if (success) { log.debug("eme: successfully loaded session"); return just(session); } log.warn("eme: no data stored for the loaded session, removing it", storedSessionId); $storedSessions["delete"](initData); $loadedSessions["delete"](storedSessionId); var sessionToRemove = session; sessionToRemove.remove()["catch"](function (err) { return log.warn("eme: could not remove session", err); }); var newSession = makeNewSessionAndCreateKeyRequest(mediaKeys, sessionType, initDataType, initData); return merge(newSession, just(sessionToRemove)); }); } // listen to "message" events from session containing a challenge // blob and map them to licenses using the getLicense method from // selected keySystem function handleMessageEvents(session, keySystem) { log.debug("eme: handle message events for session", session.sessionId); var sessionId = undefined; var keyErrors = onKeyError(session).map(function (err) { return logAndThrow("eme: keyerror event " + err.errorCode + " / " + err.systemCode, err); }); var keyStatusesChanges = onKeyStatusesChange(session).flatMap(function (keyStatusesEvent) { sessionId = keyStatusesEvent.sessionId; log.debug("eme: keystatuseschange event", sessionId, session, keyStatusesEvent); // find out possible errors associated with this event var keyStatuses = session.keyStatuses.values(); for (var v = keyStatuses.next(); !v.done; v = keyStatuses.next()) { var errMessage = KEY_STATUS_ERRORS[v.value]; if (errMessage) { logAndThrow(errMessage); } } // otherwise use the keysystem handler if disponible if (!keySystem.onKeyStatusesChange) { log.warn("eme: keystatuseschange event not handled"); return empty(); } var license = undefined; try { license = keySystem.onKeyStatusesChange(keyStatusesEvent, session); } catch (e) { license = Observable["throw"](e); } return toObservable(license)["catch"](function (err) { return logAndThrow("eme: onKeyStatusesChange has failed " + ("(reason:" + (err && err.message || "unknown") + ")"), err); }); }); var keyMessages = onKeyMessage(session).flatMap(function (messageEvent) { sessionId = messageEvent.sessionId; var message = new Uint8Array(messageEvent.message); var messageType = messageEvent.messageType || "license-request"; log.debug("eme: event message type " + messageType, session, messageEvent); var license = undefined; try { license = keySystem.getLicense(message, messageType); } catch (e) { license = Observable["throw"](e); } return toObservable(license)["catch"](function (err) { return logAndThrow("eme: getLicense has failed " + ("(reason: " + (err && err.message || "unknown") + ")"), err); }); }); var sessionUpdates = merge(keyMessages, keyStatusesChanges).concatMap(function (res) { log.debug("eme: update session", sessionId, res); return session.update(res, sessionId)["catch"](function (err) { return logAndThrow("eme: error on session update " + sessionId, err); }); }).map(function () { return { type: "eme", value: { session: session, name: "session-updated" } }; }); return merge(sessionUpdates, keyErrors); } return combineLatest(onEncrypted(video), findCompatibleKeySystem(keySystems), function (evt, ks) { return [evt, ks]; }).take(1).flatMap(function (_ref4) { var evt = _ref4[0]; var ks = _ref4[1]; return handleEncryptedEvents(evt, ks); }); } EME.onEncrypted = onEncrypted; EME.getCurrentKeySystem = function () { return $keySystem && $keySystem.type; }; EME.dispose = function () { $mediaKeys = null; $keySystem = null; $loadedSessions.dispose(); }; module.exports = EME; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var assert = __webpack_require__(2); var _require = __webpack_require__(12); var getAdaptationsByType = _require.getAdaptationsByType; var Template = __webpack_require__(30); var Timeline = __webpack_require__(18); var List = __webpack_require__(29); var Base = __webpack_require__(28); function OutOfIndexError(type) { this.name = "OutOfIndexError"; this.type = type; this.message = "out of range in index " + type; } OutOfIndexError.prototype = new Error(); function selectIndexHandler(index) { switch (index.indexType) { case "template": return Template; case "timeline": return Timeline; case "list": return List; case "base": return Base; default: throw new Error("index-handler: unrecognized indexType " + index.indexType); } } function getLiveEdge(manifest) { // TODO(pierre): improve index access ? var videoAda = getAdaptationsByType(manifest, "video"); var videoIdx = videoAda[0].representations[0].index; return selectIndexHandler(videoIdx).getLiveEdge(videoIdx, manifest); } var IndexHandler = (function () { function IndexHandler(adaptation, representation) { _classCallCheck(this, IndexHandler); this.adaptation = adaptation; this.representation = representation; this.index = representation.index; this.handler = new (selectIndexHandler(this.index))(this.index); } IndexHandler.prototype.getInitSegment = function getInitSegment() { var initialization = this.index.initialization || {}; return { id: "init_" + this.adaptation.id + "_" + this.representation.id, init: true, media: initialization.media, range: initialization.range, indexRange: this.index.indexRange }; }; IndexHandler.prototype.normalizeRange = function normalizeRange(ts, offset, bufSize) { var presentationOffset = this.index.presentationTimeOffset || 0; var timescale = this.index.timescale || 1; if (!offset) offset = 0; if (!bufSize) bufSize = 0; offset = Math.min(offset, bufSize); return { time: ts * timescale - presentationOffset, up: (ts + offset) * timescale - presentationOffset, to: (ts + bufSize) * timescale - presentationOffset }; }; IndexHandler.prototype.getSegments = function getSegments(ts, offset, bufSize) { var _normalizeRange = this.normalizeRange(ts, offset, bufSize); var time = _normalizeRange.time; var up = _normalizeRange.up; var to = _normalizeRange.to; if (!this.handler.checkRange(time)) { throw new OutOfIndexError(this.index.indexType); } return this.handler.getSegments(up, to); }; IndexHandler.prototype.insertNewSegments = function insertNewSegments(nextSegments, currentSegment) { var addedSegments = []; for (var i = 0; i < nextSegments.length; i++) { if (this.handler.addSegment(nextSegments[i], currentSegment)) { addedSegments.push(nextSegments[i]); } } return addedSegments; }; IndexHandler.prototype.setTimescale = function setTimescale(timescale) { var index = this.index; if (false) { assert(typeof timescale == "number"); assert(timescale > 0); } if (index.timescale !== timescale) { index.timescale = timescale; return true; } return false; }; IndexHandler.prototype.scale = function scale(time) { if (false) { assert(this.index.timescale > 0); } return time / this.index.timescale; }; return IndexHandler; })(); module.exports = { OutOfIndexError: OutOfIndexError, IndexHandler: IndexHandler, getLiveEdge: getLiveEdge }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _ = __webpack_require__(1); function getTimelineBound(_ref) { var ts = _ref.ts; var d = _ref.d; var r = _ref.r; if (d === -1) return ts;else return ts + (r + 1) * d; } var Timeline = (function () { function Timeline(index) { _classCallCheck(this, Timeline); this.index = index; this.timeline = index.timeline; } Timeline.getLiveEdge = function getLiveEdge(videoIndex, manifest) { var calculatedLiveEdge = getTimelineBound(_.last(videoIndex.timeline)) / videoIndex.timescale - manifest.suggestedPresentationDelay; var minimumLiveEdge = videoIndex.timeline[0].ts / videoIndex.timescale + 1.0; return Math.max(minimumLiveEdge, calculatedLiveEdge); }; Timeline.prototype.createSegment = function createSegment(time, range, duration) { return { id: time, media: this.index.media, time: time, number: undefined, range: range, duration: duration }; }; Timeline.prototype.calculateRepeat = function calculateRepeat(seg, nextSeg) { var rep = seg.r || 0; // A negative value of the @r attribute of the S element indicates // that the duration indicated in @d attribute repeats until the // start of the next S element, the end of the Period or until the // next MPD update. if (rep < 0) { var repEnd = nextSeg ? nextSeg.t : Infinity; rep = Math.ceil((repEnd - seg.ts) / seg.d) - 1; } return rep; }; Timeline.prototype.checkRange = function checkRange(up) { var last = _.last(this.timeline); if (!last) return true; if (last.d < 0) last = { ts: last.ts, d: 0, r: last.r }; return up <= getTimelineBound(last); }; Timeline.prototype.getSegmentIndex = function getSegmentIndex(ts) { var timeline = this.timeline; var low = 0; var high = timeline.length; while (low < high) { var mid = low + high >>> 1; if (timeline[mid].ts < ts) { low = mid + 1; } else { high = mid; } } return low > 0 ? low - 1 : low; }; Timeline.prototype.getSegmentNumber = function getSegmentNumber(ts, up, duration) { var diff = up - ts; if (diff > 0) return Math.floor(diff / duration);else return 0; }; Timeline.prototype.getSegments = function getSegments(up, to) { var timeline = this.index.timeline; var segments = []; var timelineLength = timeline.length; var timelineIndex = this.getSegmentIndex(up) - 1; // TODO(pierre): use @maxSegmentDuration if possible var maxDuration = timeline.length && timeline[0].d || 0; loop: for (;;) { if (++timelineIndex >= timelineLength) break; var segmentRange = timeline[timelineIndex]; var d = segmentRange.d; var ts = segmentRange.ts; var range = segmentRange.range; maxDuration = Math.max(maxDuration, d); // live-added segments have @d attribute equals to -1 if (d < 0) { if (ts + maxDuration < to) { segments.push(this.createSegment(ts, range, undefined)); } break; } var repeat = this.calculateRepeat(segmentRange, timeline[timelineIndex + 1]); var segmentNumber = this.getSegmentNumber(ts, up, d); var segmentTime; while ((segmentTime = ts + segmentNumber * d) < to) { if (segmentNumber++ <= repeat) { segments.push(this.createSegment(segmentTime, range, d)); } else { continue loop; } } break; } return segments; }; Timeline.prototype.addSegment = function addSegment(newSegment, currentSegment) { var timeline = this.timeline; var timelineLength = timeline.length; var last = timeline[timelineLength - 1]; // in some circumstances, the new segment informations are only // duration informations that we can use de deduct the ts of the // next segment. this is the case where the new segment are // associated to a current segment and have the same ts var shouldDeductNextSegment = !!currentSegment && newSegment.ts === currentSegment.ts; if (shouldDeductNextSegment) { var newSegmentTs = newSegment.ts + newSegment.d; var lastSegmentTs = last.ts + last.d * last.r; var tsDiff = newSegmentTs - lastSegmentTs; if (tsDiff <= 0) return false; // try to use the compact notation with @r attribute on the last // to elements of the timeline if we find out they have the same // duration if (last.d === -1) { var prev = timeline[timelineLength - 2]; if (prev && prev.d === tsDiff) { prev.r++; timeline.pop(); } else { last.d = tsDiff; } } timeline.push({ d: -1, ts: newSegmentTs, r: 0 }); return true; } // if the given timing has a timestamp after le timeline bound we // just need to push a new element in the timeline, or increase // the @r attribute of the last element. else if (newSegment.ts >= getTimelineBound(last)) { if (last.d === newSegment.d) { last.r++; } else { timeline.push({ d: newSegment.d, ts: newSegment.ts, r: 0 }); } return true; } return false; }; return Timeline; })(); module.exports = Timeline; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _require = __webpack_require__(3); var Observable = _require.Observable; var _require2 = __webpack_require__(9); var BufferedRanges = _require2.BufferedRanges; // time changes interval in milliseconds var TIMINGS_SAMPLING_INTERVAL = 1000; // time in seconds protecting live buffer to prevent ahead of time // buffering var LIVE_PROTECTION = 10; // stall gap in seconds var STALL_GAP = 0.5; var RESUME_GAP = 5; // seek gap in seconds var SEEK_GAP = 2; // waiting time differs between a "seeking" stall and // a buffering stall function resumeGap(stalled) { return stalled.name == "seeking" ? STALL_GAP : RESUME_GAP; } function isEnding(gap, range, duration) { if (range) { return duration - (gap + range.end) <= STALL_GAP; } else { return false; } } function getEmptyTimings() { return { name: "timeupdate", ts: 0, range: null, gap: Infinity, duration: 0, playback: 1, readyState: 0, stalled: false, buffered: new BufferedRanges() }; } function getTimings(video, name) { var playback = video.playbackRate; var duration = video.duration; var ts = video.currentTime; var readyState = video.readyState; var buffered = new BufferedRanges(video.buffered); var range = buffered.getRange(ts); var gap = buffered.getGap(ts); var stalled = null; return { name: name, ts: ts, range: range, gap: gap, duration: duration, playback: playback, readyState: readyState, stalled: stalled, buffered: buffered }; } /** * Timings observable. * * This streams samples snapshots of player's current state: * * time position * * playback rate * * current buffered range * * gap with current buffered range ending * * video duration * * In addition to sampling, this stream also reacts to "seeking" and "play" * events. * * Observable is shared for performance reason: reduces the number of event * listeners and intervals/timeouts but also limit access to <video> * properties and gap calculations. * * The sampling is manual instead of based on "timeupdate" to reduce the * number of events. */ function timingsSampler(video) { function scanTimingsSamples(prevTimings, timingEventType) { var currentTimings = getTimings(video, timingEventType); var wasStalled = prevTimings.stalled; var currentGap = currentTimings.gap; var hasStalled = timingEventType != "loadedmetadata" && !wasStalled && !isEnding(currentGap, currentTimings.range, currentTimings.duration) && (currentGap <= STALL_GAP || currentGap === Infinity); var stalled; if (hasStalled) { stalled = { name: currentTimings.name, playback: currentTimings.playback }; } else if (wasStalled && currentGap < Infinity && currentGap > resumeGap(wasStalled)) { stalled = null; } else { stalled = wasStalled; } currentTimings.stalled = stalled; return currentTimings; } return Observable.create(function (obs) { var prevTimings = getTimings(video, "init"); function emitSample(evt) { var timingEventType = evt && evt.type || "timeupdate"; prevTimings = scanTimingsSamples(prevTimings, timingEventType); obs.onNext(prevTimings); } var samplerInterval = setInterval(emitSample, TIMINGS_SAMPLING_INTERVAL); video.addEventListener("play", emitSample); video.addEventListener("progress", emitSample); video.addEventListener("seeking", emitSample); video.addEventListener("seeked", emitSample); video.addEventListener("loadedmetadata", emitSample); obs.onNext(prevTimings); return function () { clearInterval(samplerInterval); video.removeEventListener("play", emitSample); video.removeEventListener("progress", emitSample); video.removeEventListener("seeking", emitSample); video.removeEventListener("seeked", emitSample); video.removeEventListener("loadedmetadata", emitSample); }; }).shareValue({ name: "init", stalled: null }); } function seekingsSampler(timingsSampling) { return timingsSampling.filter(function (t) { return t.name == "seeking" && (t.gap === Infinity || t.gap < -SEEK_GAP); }) // skip the first seeking event generated by the set of the // initial seeking time in the video .skip(1).startWith(true); } function toWallClockTime(ts, manifest) { return new Date((ts + manifest.availabilityStartTime) * 1000); } function fromWallClockTime(timeInMs, manifest) { return normalizeWallClockTime(timeInMs, manifest) / 1000 - manifest.availabilityStartTime; } function normalizeWallClockTime(timeInMs, manifest) { var suggestedPresentationDelay = manifest.suggestedPresentationDelay; var presentationLiveGap = manifest.presentationLiveGap; var timeShiftBufferDepth = manifest.timeShiftBufferDepth; if (typeof timeInMs != "number") timeInMs = timeInMs.getTime(); var now = Date.now(); var max = now - (presentationLiveGap + suggestedPresentationDelay) * 1000; var min = now - timeShiftBufferDepth * 1000; return Math.max(Math.min(timeInMs, max), min); } function getLiveGap(ts, manifest) { if (!manifest.isLive) return Infinity; var availabilityStartTime = manifest.availabilityStartTime; var presentationLiveGap = manifest.presentationLiveGap; var liveGap = Date.now() / 1000 - ts; return liveGap - (availabilityStartTime + presentationLiveGap + LIVE_PROTECTION); } module.exports = { getEmptyTimings: getEmptyTimings, getTimings: getTimings, timingsSampler: timingsSampler, seekingsSampler: seekingsSampler, getLiveGap: getLiveGap, toWallClockTime: toWallClockTime, fromWallClockTime: fromWallClockTime }; /***/ }, /* 20 */ /***/ function(module, exports) { "use strict"; var FUZZ_FACTOR = 0.3; function getFuzzedDelay(retryDelay) { var fuzzingFactor = (Math.random() * 2 - 1) * FUZZ_FACTOR; return retryDelay * (1.0 + fuzzingFactor); } function getBackedoffDelay(retryDelay) { var retryCount = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1]; return getFuzzedDelay(retryDelay * Math.pow(2, retryCount - 1)); } module.exports = { getFuzzedDelay: getFuzzedDelay, getBackedoffDelay: getBackedoffDelay }; /***/ }, /* 21 */ /***/ function(module, exports) { "use strict"; module.exports = function (fn, wait, debounceOptions) { var timer = null; var stamp = 0; var args = []; var leading = !!(debounceOptions && debounceOptions.leading); var calledOnce = false; function onCall() { var dt = stamp - Date.now(); if (dt > 0) { timer = setTimeout(onCall, dt); } else { timer = null; switch (args.length) { case 0: return fn(); case 1: return fn(args[0]); case 2: return fn(args[0], args[1]); case 3: return fn(args[0], args[1], args[2]); default: return fn.apply(null, args); } } } function debounced() { // do not leak arguments object to prevent de-optimizations var l = arguments.length, i = 0; args = Array(l); for (; i < l; i++) args[i] = arguments[i]; if (leading && !calledOnce) { calledOnce = true; stamp = Date.now(); return onCall(); } var t = stamp; stamp = Date.now() + wait; if (!timer || stamp < t) { if (timer) clearTimeout(timer); timer = setTimeout(onCall, wait); } return debounced; } debounced.isWaiting = function () { return !!timer; }; debounced.dispose = function () { if (timer) { clearTimeout(timer); timer = null; } }; return debounced; }; /***/ }, /* 22 */ /***/ function(module, exports) { "use strict"; module.exports = function (module) { if (!module.webpackPolyfill) { module.deprecate = function () {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; }; /***/ }, /* 23 */ /***/ function(module, exports) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Average bandwidth rule */ // Exponential moving-average // http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average "use strict"; function ema(a) { return function (s, x) { return s == null ? x : a * x + (1 - a) * s; }; } module.exports = function (metrics, options) { return metrics.map(function (metric) { return metric.value.response; }) // do not take into account small chunks < 2KB. filters out init // segments and small manifests in particular. .filter(function (response) { return response.size > 2000; }) // converts response metadata in bits-per-seconds .map(function (response) { return response.size / response.duration * 8000; }).scan(ema(options.alpha)); }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var log = __webpack_require__(4); var _require = __webpack_require__(3); var Observable = _require.Observable; var BehaviorSubject = _require.BehaviorSubject; var CompositeDisposable = _require.CompositeDisposable; var combineLatest = Observable.combineLatest; var _require2 = __webpack_require__(5); var only = _require2.only; var AverageBitrate = __webpack_require__(23); var DEFAULTS = { defaultLanguage: "fra", defaultSubtitle: "", // default buffer size in seconds defaultBufferSize: 30, // buffer threshold ratio used as a lower bound // margin to find the suitable representation defaultBufferThreshold: 0.3 }; function def(x, val) { return typeof x == "number" && x > 0 ? x : val; } function getClosestBitrate(bitrates, btr) { var threshold = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; return _.findLast(bitrates, function (b) { return b / btr <= 1 - threshold; }) || bitrates[0]; } function getClosestDisplayBitrate(reps, width) { var rep = _.find(reps, function (r) { return r.width >= width; }); if (rep) return rep.bitrate;else return Infinity; } function findByLang(adaptations, lang) { if (lang) { return _.find(adaptations, function (a) { return a.lang === lang; }); } else { return null; } } function filterByType(stream, selectedType) { return stream.filter(function (_ref) { var type = _ref.type; return type === selectedType; }); } module.exports = function (metrics, timings, deviceEvents) { var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; var _$defaults = _.defaults(options, DEFAULTS); var defaultLanguage = _$defaults.defaultLanguage; var defaultSubtitle = _$defaults.defaultSubtitle; var defaultBufferSize = _$defaults.defaultBufferSize; var defaultBufferThreshold = _$defaults.defaultBufferThreshold; var initVideoBitrate = _$defaults.initVideoBitrate; var initAudioBitrate = _$defaults.initAudioBitrate; var videoWidth = deviceEvents.videoWidth; var inBackground = deviceEvents.inBackground; var $languages = new BehaviorSubject(defaultLanguage); var $subtitles = new BehaviorSubject(defaultSubtitle); var $averageBitrates = { audio: AverageBitrate(filterByType(metrics, "audio"), { alpha: 0.6 }).publishValue(initAudioBitrate || 0), video: AverageBitrate(filterByType(metrics, "video"), { alpha: 0.6 }).publishValue(initVideoBitrate || 0) }; var conns = new CompositeDisposable(_.map(_.values($averageBitrates), function (a) { return a.connect(); })); var $usrBitrates = { audio: new BehaviorSubject(Infinity), video: new BehaviorSubject(Infinity) }; var $maxBitrates = { audio: new BehaviorSubject(Infinity), video: new BehaviorSubject(Infinity) }; var $bufSizes = { audio: new BehaviorSubject(defaultBufferSize), video: new BehaviorSubject(defaultBufferSize), text: new BehaviorSubject(defaultBufferSize) }; function audioAdaptationChoice(adaptations) { return $languages.changes().map(function (lang) { return findByLang(adaptations, lang) || adaptations[0]; }); } function textAdaptationChoice(adaptations) { return $subtitles.changes().map(function (lang) { return findByLang(adaptations, lang); }); } function getAdaptationsChoice(type, adaptations) { if (type == "audio") return audioAdaptationChoice(adaptations); if (type == "text") return textAdaptationChoice(adaptations); if (adaptations.length == 1) return only(adaptations[0]); throw new Error("adaptive: unknown type " + type + " for adaptation chooser"); } function getBufferAdapters(adaptation) { var type = adaptation.type; var bitrates = adaptation.bitrates; var representations = adaptation.representations; var firstRep = representations[0]; var representationsObservable; if (representations.length > 1) { var usrBitrates = $usrBitrates[type]; var maxBitrates = $maxBitrates[type]; var avrBitrates = $averageBitrates[type].map(function (avrBitrate, count) { // no threshold for the first value of the average bitrate // stream corresponding to the selected initial video bitrate var bufThreshold; if (count === 0) bufThreshold = 0;else bufThreshold = defaultBufferThreshold; return getClosestBitrate(bitrates, avrBitrate, bufThreshold); }).changes().customDebounce(2000, { leading: true }); if (type == "video") { // To compute the bitrate upper-bound for video // representations we need to combine multiple stream: // - user-based maximum bitrate (subject) // - maximum based on the video element width // - maximum based on the application visibility (background tab) maxBitrates = combineLatest(maxBitrates, videoWidth, inBackground, function (bitrate, width, isHidden) { if (isHidden) return bitrates[0]; var closestDisplayBitrate = getClosestDisplayBitrate(representations, width); if (closestDisplayBitrate < bitrate) return closestDisplayBitrate; return bitrate; }); } representationsObservable = combineLatest(usrBitrates, maxBitrates, avrBitrates, function (usr, max, avr) { if (usr < Infinity) return usr; if (max < Infinity) return Math.min(max, avr); return avr; }).map(function (b) { return _.find(representations, function (rep) { return rep.bitrate === getClosestBitrate(bitrates, b); }); }).changes(function (r) { return r.id; }).tap(function (r) { return log.info("bitrate", type, r.bitrate); }); } else { representationsObservable = only(firstRep); } return { representations: representationsObservable, bufferSizes: $bufSizes[type] || new BehaviorSubject(defaultBufferSize) }; } return { setLanguage: function setLanguage(lng) { $languages.onNext(lng); }, setSubtitle: function setSubtitle(sub) { $subtitles.onNext(sub); }, getLanguage: function getLanguage() { return $languages.value; }, getSubtitle: function getSubtitle() { return $subtitles.value; }, getAverageBitrates: function getAverageBitrates() { return $averageBitrates; }, getAudioMaxBitrate: function getAudioMaxBitrate() { return $maxBitrates.audio.value; }, getVideoMaxBitrate: function getVideoMaxBitrate() { return $maxBitrates.video.value; }, getAudioBufferSize: function getAudioBufferSize() { return $bufSizes.audio.value; }, getVideoBufferSize: function getVideoBufferSize() { return $bufSizes.video.value; }, setAudioBitrate: function setAudioBitrate(x) { $usrBitrates.audio.onNext(def(x, Infinity)); }, setVideoBitrate: function setVideoBitrate(x) { $usrBitrates.video.onNext(def(x, Infinity)); }, setAudioMaxBitrate: function setAudioMaxBitrate(x) { $maxBitrates.audio.onNext(def(x, Infinity)); }, setVideoMaxBitrate: function setVideoMaxBitrate(x) { $maxBitrates.video.onNext(def(x, Infinity)); }, setAudioBufferSize: function setAudioBufferSize(x) { $bufSizes.audio.onNext(def(x, defaultBufferSize)); }, setVideoBufferSize: function setVideoBufferSize(x) { $bufSizes.video.onNext(def(x, defaultBufferSize)); }, getBufferAdapters: getBufferAdapters, getAdaptationsChoice: getAdaptationsChoice, dispose: function dispose() { if (conns) { conns.dispose(); conns = null; } } }; }; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var log = __webpack_require__(4); var assert = __webpack_require__(2); var _require = __webpack_require__(9); var BufferedRanges = _require.BufferedRanges; var _require2 = __webpack_require__(3); var Observable = _require2.Observable; var Subject = _require2.Subject; var combineLatest = Observable.combineLatest; var defer = Observable.defer; var empty = Observable.empty; var from = Observable.from; var just = Observable.just; var merge = Observable.merge; var timer = Observable.timer; var _require3 = __webpack_require__(5); var first = _require3.first; var on = _require3.on; var _require4 = __webpack_require__(46); var ArraySet = _require4.ArraySet; var _require5 = __webpack_require__(17); var IndexHandler = _require5.IndexHandler; var OutOfIndexError = _require5.OutOfIndexError; var BITRATE_REBUFFERING_RATIO = 1.5; var GC_GAP_CALM = 240; var GC_GAP_BEEFY = 30; function Buffer(_ref) // Timings observable // Seekings observable { var sourceBuffer = _ref.sourceBuffer; var // SourceBuffer object adaptation = _ref.adaptation; var // Adaptation buffered pipeline = _ref.pipeline; var // Segment pipeline adapters = _ref.adapters; var // { representations, bufferSizes } observables timings = _ref.timings; var seekings = _ref.seekings; var bufferType = adaptation.type; var isAVBuffer = bufferType == "audio" || bufferType == "video"; var outOfIndexStream = new Subject(); // safety level (low and high water mark) size of buffer that won't // be flushed when switching representation for smooth transitions // and avoiding buffer underflows var LOW_WATER_MARK_PAD = bufferType == "video" ? 4 : 1; var HIGH_WATER_MARK_PAD = bufferType == "video" ? 6 : 1; var representations = adapters.representations; var bufferSizes = adapters.bufferSizes; var ranges = new BufferedRanges(); var updateEnd = merge(on(sourceBuffer, "update"), on(sourceBuffer, "error").map(function (evt) { if (evt.target && evt.target.error) { throw evt.target.error; } else { var errMessage = "buffer: error event"; log.error(errMessage, evt); throw new Error(errMessage); } })).share(); // prevents unceasing add/remove event listeners by sharing an // open updateEnd stream (hackish) var mutedUpdateEnd = updateEnd.ignoreElements().startWith(true); function appendBuffer(blob) { sourceBuffer.appendBuffer(blob); return first(updateEnd); } function removeBuffer(_ref2) { var start = _ref2.start; var end = _ref2.end; sourceBuffer.remove(start, end); return first(updateEnd); } function lockedBufferFunction(func) { return function (data) { return defer(function () { if (sourceBuffer.updating) { return first(updateEnd).flatMap(function () { return func(data); }); } else { return func(data); } }); }; } var lockedAppendBuffer = lockedBufferFunction(appendBuffer); var lockedRemoveBuffer = lockedBufferFunction(removeBuffer); // Buffer garbage collector algorithm. Tries to free up some part of // the ranges that are distant from the current playing time. // See: https://w3c.github.io/media-source/#sourcebuffer-prepare-append function selectGCedRanges(_ref3, gcGap) { var ts = _ref3.ts; var buffered = _ref3.buffered; var innerRange = buffered.getRange(ts); var outerRanges = buffered.getOuterRanges(ts); var cleanedupRanges = []; // start by trying to remove all ranges that do not contain the // current time and respect the gcGap for (var i = 0; i < outerRanges.length; i++) { var outerRange = outerRanges[i]; if (ts - gcGap < outerRange.end) { cleanedupRanges.push(outerRange); } else if (ts + gcGap > outerRange.start) { cleanedupRanges.push(outerRange); } } // try to clean up some space in the current range if (innerRange) { log.debug("buffer: gc removing part of inner range", cleanedupRanges); if (ts - gcGap > innerRange.start) { cleanedupRanges.push({ start: innerRange.start, end: ts - gcGap }); } if (ts + gcGap < innerRange.end) { cleanedupRanges.push({ start: ts + gcGap, end: innerRange.end }); } } return cleanedupRanges; } function bufferGarbageCollector() { log.warn("buffer: running garbage collector"); return timings.take(1).flatMap(function (timing) { var cleanedupRanges = selectGCedRanges(timing, GC_GAP_CALM); // more aggressive GC if we could not find any range to clean if (cleanedupRanges.length === 0) { cleanedupRanges = selectGCedRanges(timing, GC_GAP_BEEFY); } log.debug("buffer: gc cleaning", cleanedupRanges); return from(cleanedupRanges.map(lockedRemoveBuffer)).concatAll(); }); } function createRepresentationBuffer(representation) { var segmentIndex = new IndexHandler(adaptation, representation); var queuedSegments = new ArraySet(); function filterAlreadyLoaded(segment) { // if this segment is already in the pipeline var isInQueue = queuedSegments.test(segment.id); if (isInQueue) return false; // segment without time info are usually init segments or some // kind of metadata segment that we never filter out if (segment.init || segment.time == null) return true; var time = segmentIndex.scale(segment.time); var duration = segmentIndex.scale(segment.duration); var range = ranges.hasRange(time, duration); if (range) { return range.bitrate * BITRATE_REBUFFERING_RATIO < representation.bitrate; } else { return true; } } function getSegmentsListToInject(buffered, timing, bufferSize, withInitSegment) { var segments = []; if (withInitSegment) { log.debug("add init segment", bufferType); segments.push(segmentIndex.getInitSegment()); } if (timing.readyState === 0) { return segments; } var timestamp = timing.ts; // wanted buffer size calculates the actual size of the buffer // we want to ensure, taking into account the duration and the // potential live gap. var endDiff = (timing.duration || Infinity) - timestamp; var wantedBufferSize = Math.max(0, Math.min(bufferSize, timing.liveGap, endDiff)); // the ts padding is the actual time gap that we want to apply // to our current timestamp in order to calculate the list of // segments to inject. var timestampPadding; var bufferGap = buffered.getGap(timestamp); if (bufferGap > LOW_WATER_MARK_PAD && bufferGap < Infinity) { timestampPadding = Math.min(bufferGap, HIGH_WATER_MARK_PAD); } else { timestampPadding = 0; } // in case the current buffered range has the same bitrate as // the requested representation, we can a optimistically discard // all the already buffered data by using the var currentRange = ranges.getRange(timestamp); if (currentRange && currentRange.bitrate === representation.bitrate) { var rangeEndGap = Math.floor(currentRange.end - timestamp); if (rangeEndGap > timestampPadding) timestampPadding = rangeEndGap; } // given the current timestamp and the previously calculated // time gap and wanted buffer size, we can retrieve the list of // segments to inject in our pipelines. var mediaSegments = segmentIndex.getSegments(timestamp, timestampPadding, wantedBufferSize); return segments.concat(mediaSegments); } var segmentsPipeline = combineLatest(timings, bufferSizes, mutedUpdateEnd, function (timing, bufferSize) { return { timing: timing, bufferSize: bufferSize }; }).flatMap(function (_ref4, count) { var timing = _ref4.timing; var bufferSize = _ref4.bufferSize; var nativeBufferedRanges = new BufferedRanges(sourceBuffer.buffered); // makes sure our own buffered ranges representation stay in // sync with the native one if (isAVBuffer) { if (!ranges.equals(nativeBufferedRanges)) { log.debug("intersect new buffer", bufferType); ranges.intersect(nativeBufferedRanges); } } var injectedSegments; try { // filter out already loaded and already queued segments var withInitSegment = count === 0; injectedSegments = getSegmentsListToInject(nativeBufferedRanges, timing, bufferSize, withInitSegment); injectedSegments = _.filter(injectedSegments, filterAlreadyLoaded); } catch (err) { // catch OutOfIndexError errors thrown by when we try to // access to non available segments. Reinject this error // into the main buffer observable so that it can be treated // upstream if (err instanceof OutOfIndexError) { outOfIndexStream.onNext({ type: "out-of-index", value: err }); return empty(); } else { throw err; } // unreachable assert(false); } return from(_.map(injectedSegments, function (segment) { // queue all segments injected in the observable queuedSegments.add(segment.id); return { adaptation: adaptation, representation: representation, segment: segment }; })); }).concatMap(pipeline).concatMap(function (infos) { var blob = infos.parsed.blob; return lockedAppendBuffer(blob)["catch"](function (err) { // launch our garbage collector and retry on // QuotaExceededError if (err.name == "QuotaExceededError") { return bufferGarbageCollector().flatMap(function () { return lockedAppendBuffer(blob); }); } else { throw err; } }).map(infos); }).map(function (infos) { var segment = infos.segment; var parsed = infos.parsed; queuedSegments.remove(segment.id); // change the timescale if one has been extracted from the // parsed segment (SegmentBase) var timescale = parsed.timescale; if (timescale) { segmentIndex.setTimescale(timescale); } var nextSegments = parsed.nextSegments; var currentSegment = parsed.currentSegment; // added segments are values parsed from the segment metadata // that should be added to the segmentIndex. var addedSegments; if (nextSegments) { addedSegments = segmentIndex.insertNewSegments(nextSegments, currentSegment); } else { addedSegments = []; } // current segment timings informations are used to update // ranges informations if (currentSegment) { ranges.insert(representation.bitrate, segmentIndex.scale(currentSegment.ts), segmentIndex.scale(currentSegment.ts + currentSegment.d)); } return { type: "segment", value: _.extend({ addedSegments: addedSegments }, infos) }; }); return merge(segmentsPipeline, outOfIndexStream)["catch"](function (err) { if (err.code !== 412) throw err; // 412 Precondition Failed request errors do not cause the // buffer to stop but are re-emitted in the stream as // "precondition-failed" type. They should be handled re- // adapting the live-gap that the player is holding return just({ type: "precondition-failed", value: err }).concat(timer(2000)).concat(createRepresentationBuffer(representation)); }); } return combineLatest(representations, seekings, _.identity).flatMapLatest(createRepresentationBuffer); } module.exports = Buffer; /***/ }, /* 26 */ /***/ function(module, exports) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Caching object used to cache initialization segments. * This allow to have a faster representation switch and seeking. */ "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var InitializationSegmentCache = (function () { function InitializationSegmentCache() { _classCallCheck(this, InitializationSegmentCache); this.cache = {}; } InitializationSegmentCache.prototype.add = function add(_ref, loaded) { var segment = _ref.segment; if (segment.init) { this.cache[segment.id] = loaded; } }; InitializationSegmentCache.prototype.get = function get(_ref2) { var segment = _ref2.segment; if (segment.init) { var value = this.cache[segment.id]; if (value != null) return value; } return null; }; return InitializationSegmentCache; })(); module.exports = { InitializationSegmentCache: InitializationSegmentCache }; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _require = __webpack_require__(3); var Observable = _require.Observable; var merge = Observable.merge; var interval = Observable.interval; var _require2 = __webpack_require__(8); var visibilityChange = _require2.visibilityChange; var videoSizeChange = _require2.videoSizeChange; var INACTIVITY_DELAY = 60 * 1000; var pixelRatio = window.devicePixelRatio || 1; function DeviceEvents(videoElement) { var isVisible = visibilityChange().filter(function (x) { return x === false; }); var isHidden = visibilityChange().customDebounce(INACTIVITY_DELAY).filter(function (x) { return x === true; }); var inBackground = merge(isVisible, isHidden).startWith(false); var videoWidth = merge(interval(20000), videoSizeChange().customDebounce(500)).startWith("init").map(function () { return videoElement.clientWidth * pixelRatio; }).changes(); return { videoWidth: videoWidth, inBackground: inBackground }; } module.exports = DeviceEvents; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; 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) : subClass.__proto__ = superClass; } var Timeline = __webpack_require__(18); var Base = (function (_Timeline) { _inherits(Base, _Timeline); function Base(index) { _classCallCheck(this, Base); _Timeline.call(this, index); } Base.getLiveEdge = function getLiveEdge() { throw new Error("not implemented"); }; Base.prototype.addSegment = function addSegment(newSegment) { this.index.timeline.push(newSegment); return true; }; return Base; })(Timeline); module.exports = Base; /***/ }, /* 29 */ /***/ function(module, exports) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var List = (function () { function List(index) { _classCallCheck(this, List); this.index = index; } List.getLiveEdge = function getLiveEdge() { throw new Error("not implemented"); }; List.prototype.checkRange = function checkRange(up) { var _index = this.index; var duration = _index.duration; var list = _index.list; var i = Math.floor(up / duration); return i >= 0 && i < list.length; }; List.prototype.createSegment = function createSegment(segmentIndex, time) { var segment = this.index.list[segmentIndex]; return { id: segmentIndex, media: segment.media, time: time, number: undefined, range: segment.range, duration: this.index.duration }; }; List.prototype.getSegments = function getSegments(up, to) { // TODO(pierre): use startNumber var duration = this.index.duration; var i = Math.floor(up / duration); var l = Math.floor(to / duration); var segments = []; while (i < l) { segments.push(this.createSegment(i, i * duration)); i++; } return segments; }; List.prototype.addSegment = function addSegment() { return false; }; return List; })(); module.exports = List; /***/ }, /* 30 */ /***/ function(module, exports) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Template = (function () { function Template(index) { _classCallCheck(this, Template); this.index = index; } Template.getLiveEdge = function getLiveEdge(videoIndex, manifest) { return Date.now() / 1000 - manifest.availabilityStartTime - manifest.suggestedPresentationDelay; }; Template.prototype.checkRange = function checkRange() { return true; }; Template.prototype.createSegment = function createSegment(ts) { var _index = this.index; var startNumber = _index.startNumber; var duration = _index.duration; if (startNumber == null) startNumber = 1; var number = Math.floor(ts / duration) + startNumber; var time = number * duration; return { id: number, media: this.index.media, time: time, number: number, range: undefined, duration: this.index.duration }; }; Template.prototype.getSegments = function getSegments(up, to) { var duration = this.index.duration; var segments = []; for (var time = up; time <= to; time += duration) { segments.push(this.createSegment(time)); } return segments; }; Template.prototype.addSegment = function addSegment() { return false; }; return Template; })(); module.exports = Template; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var _require = __webpack_require__(3); var Subject = _require.Subject; var Observable = _require.Observable; var _require2 = __webpack_require__(5); var retryWithBackoff = _require2.retryWithBackoff; var fromPromise = Observable.fromPromise; var just = Observable.just; var noCache = { add: function add() {}, get: function get() { return null; } }; /** * Creates the following pipeline: * Infos * => [resolver] Infos -> ResolvedInfos * => [loader] ResolvedInfos -> Response * => [parser] (Response, ResolvedInfos) -> ParsedInfos * => { ...ResolvedInfos, ...ParsedInfos } * * TODO(pierre): create a pipeline patcher to work over a WebWorker */ function createPipeline(type, _ref, metrics) { var resolver = _ref.resolver; var loader = _ref.loader; var parser = _ref.parser; var opts = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; if (!parser) parser = just; if (!loader) loader = just; if (!resolver) resolver = just; var _$defaults = _.defaults(opts, { totalRetry: 3, timeout: 10 * 1000, cache: noCache }); var totalRetry = _$defaults.totalRetry; var timeout = _$defaults.timeout; var cache = _$defaults.cache; var backoffOptions = { retryDelay: 500, totalRetry: totalRetry, shouldRetry: function shouldRetry(err) { return err.code >= 500 || err.code < 200 || /timeout/.test(err.message) || /request: error event/.test(err.message); } }; function callLoader(resolvedInfos) { return loader(resolvedInfos).simpleTimeout(timeout, "timeout").map(function (response) { var loadedInfos = _.extend({ response: response }, resolvedInfos); // add loadedInfos to the pipeline cache cache.add(resolvedInfos, loadedInfos); // emit loadedInfos in the metrics observer metrics.onNext({ type: type, value: loadedInfos }); return loadedInfos; }); } return function (infos) { return resolver(infos).flatMap(function (resolvedInfos) { var backedOffLoader = retryWithBackoff(function () { return callLoader(resolvedInfos); }, backoffOptions); var fromCache = cache.get(resolvedInfos); if (_.isPromise(fromCache)) return fromPromise(fromCache)["catch"](backedOffLoader); if (fromCache === null) return backedOffLoader();else return just(fromCache); }).flatMap(function (loadedInfos) { return parser(loadedInfos).map(function (parsed) { return _.extend({ parsed: parsed }, loadedInfos); }); }); }; } function PipeLines() { // the metrics observer/observable is used to calculate informations // about loaded responsed in the loader part of pipelines var metrics = new Subject(); var createPipelines = function createPipelines(transport, options) { options = options || {}; var ps = []; for (var pipelineType in transport) { ps[pipelineType] = createPipeline(pipelineType, transport[pipelineType], metrics, options[pipelineType]); } return ps; }; return { createPipelines: createPipelines, metrics: metrics }; } module.exports = PipeLines; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; 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) : subClass.__proto__ = superClass; } var Promise_ = __webpack_require__(6); var _ = __webpack_require__(1); var log = __webpack_require__(4); var _require = __webpack_require__(3); var CompositeDisposable = _require.CompositeDisposable; var BehaviorSubject = _require.BehaviorSubject; var Observable = _require.Observable; var Subject = _require.Subject; var combineLatest = Observable.combineLatest; var defer = Observable.defer; var _require2 = __webpack_require__(5); var on = _require2.on; var EventEmitter = __webpack_require__(10); var debugPane = __webpack_require__(47); var assert = __webpack_require__(2); var _require3 = __webpack_require__(8); var HTMLVideoElement_ = _require3.HTMLVideoElement_; var exitFullscreen = _require3.exitFullscreen; var requestFullscreen = _require3.requestFullscreen; var _isFullscreen = _require3.isFullscreen; var onFullscreenChange = _require3.onFullscreenChange; var _require4 = __webpack_require__(19); var getEmptyTimings = _require4.getEmptyTimings; var timingsSampler = _require4.timingsSampler; var toWallClockTime = _require4.toWallClockTime; var fromWallClockTime = _require4.fromWallClockTime; var getLiveGap = _require4.getLiveGap; var _require5 = __webpack_require__(26); var InitializationSegmentCache = _require5.InitializationSegmentCache; var _require6 = __webpack_require__(9); var BufferedRanges = _require6.BufferedRanges; var _require7 = __webpack_require__(36); var parseTimeFragment = _require7.parseTimeFragment; var DeviceEvents = __webpack_require__(27); var manifestHelpers = __webpack_require__(12); // TODO(pierre): separate transports from main build var Transports = __webpack_require__(40); var PipeLines = __webpack_require__(31); var Adaptive = __webpack_require__(24); var Stream = __webpack_require__(34); var EME = __webpack_require__(16); var PLAYER_STOPPED = "STOPPED"; var PLAYER_LOADED = "LOADED"; var PLAYER_LOADING = "LOADING"; var PLAYER_PLAYING = "PLAYING"; var PLAYER_PAUSED = "PAUSED"; var PLAYER_ENDED = "ENDED"; var PLAYER_BUFFERING = "BUFFERING"; var PLAYER_SEEKING = "SEEKING"; function assertMan(player) { assert(player.man, "player: no manifest loaded"); } function filterStreamByType(stream, type) { return stream.filter(function (o) { return o.type == type; }).pluck("value"); } var Player = (function (_EventEmitter) { _inherits(Player, _EventEmitter); function Player(options) { var _this = this; _classCallCheck(this, Player); var videoElement = options.videoElement; var transport = options.transport; var transportOptions = options.transportOptions; var defaultLanguage = options.defaultLanguage; var defaultSubtitle = options.defaultSubtitle; var initVideoBitrate = options.initVideoBitrate; var initAudioBitrate = options.initAudioBitrate; _EventEmitter.call(this); this.defaultTransport = transport; this.defaultTransportOptions = transportOptions || {}; if (!videoElement) videoElement = document.createElement("video"); assert(videoElement instanceof HTMLVideoElement_, "requires an actual HTMLVideoElement"); // Workaroud to support Firefox autoplay on FF 42. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1194624 videoElement.preload = "auto"; this.version = ("1.4.1"); this.video = videoElement; // fullscreen change this.fullscreen = onFullscreenChange(videoElement).subscribe(function () { return _this.trigger("fullscreenChange", _this.isFullscreen()); }); // playing state change this.playing = new BehaviorSubject(); // multicaster forwarding all streams events this.stream = new Subject(); var _PipeLines = PipeLines(); var createPipelines = _PipeLines.createPipelines; var metrics = _PipeLines.metrics; var timings = timingsSampler(videoElement); var deviceEvents = DeviceEvents(videoElement); this.createPipelines = createPipelines; this.metrics = metrics; this.timings = timings; this.adaptive = Adaptive(metrics, timings, deviceEvents, { initVideoBitrate: initVideoBitrate, initAudioBitrate: initAudioBitrate, defaultLanguage: defaultLanguage, defaultSubtitle: defaultSubtitle }); // volume muted memory this.muted = 0.1; // states this._setState(PLAYER_STOPPED); this.resetStates(); this.log = log; } Player.prototype.resetStates = function resetStates() { this.man = null; this.reps = { video: null, audio: null, text: null }; this.adas = { video: null, audio: null, text: null }; this.evts = {}; this.frag = { start: null, end: null }; }; Player.prototype._clear = function _clear() { if (this.subscriptions) { this.subscriptions.dispose(); this.subscriptions = null; } }; Player.prototype.stop = function stop() { if (this.state !== PLAYER_STOPPED) { this.resetStates(); this._clear(); this._setState(PLAYER_STOPPED); } }; Player.prototype.dispose = function dispose() { this.stop(); this.metrics.dispose(); this.adaptive.dispose(); this.fullscreen.dispose(); this.stream.dispose(); this.metrics = null; this.adaptive = null; this.fullscreen = null; this.stream = null; this.timings = null; this.createPipelines = null; this.video = null; }; Player.prototype.__recordState = function __recordState(type, value) { var prev = this.evts[type]; if (prev !== value) { this.evts[type] = value; this.trigger(type + "Change", value); } }; Player.prototype._parseOptions = function _parseOptions(opts) { var _$defaults = _.defaults(_.cloneObject(opts), { transport: this.defaultTransport, transportOptions: {}, keySystems: [], timeFragment: {}, subtitles: [], autoPlay: false, directFile: false }); var transport = _$defaults.transport; var transportOptions = _$defaults.transportOptions; var url = _$defaults.url; var manifests = _$defaults.manifests; var keySystems = _$defaults.keySystems; var timeFragment = _$defaults.timeFragment; var subtitles = _$defaults.subtitles; var autoPlay = _$defaults.autoPlay; var directFile = _$defaults.directFile; timeFragment = parseTimeFragment(timeFragment); // compatibility with old API authorizing to pass multiple // manifest url depending on the key system assert(!!manifests ^ !!url, "player: you have to pass either a url or a list of manifests"); if (manifests) { var firstManifest = manifests[0]; url = firstManifest.url; subtitles = firstManifest.subtitles || []; keySystems = _.compact(_.pluck(manifests, "keySystem")); } if (_.isString(transport)) transport = Transports[transport]; if (_.isFunction(transport)) transport = transport(_.defaults(transportOptions, this.defaultTransportOptions)); assert(transport, "player: transport " + opts.transport + " is not supported"); if (directFile) { directFile = manifestHelpers.createDirectFileManifest(); } return { url: url, keySystems: keySystems, subtitles: subtitles, timeFragment: timeFragment, autoPlay: autoPlay, transport: transport, directFile: directFile }; }; Player.prototype.loadVideo = function loadVideo() { var _this2 = this; var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; options = this._parseOptions(options); log.info("loadvideo", options); var _options = options; var url = _options.url; var keySystems = _options.keySystems; var subtitles = _options.subtitles; var timeFragment = _options.timeFragment; var autoPlay = _options.autoPlay; var transport = _options.transport; var directFile = _options.directFile; this.stop(); this.frag = timeFragment; this.playing.onNext(autoPlay); var pipelines = this.createPipelines(transport, { audio: { cache: new InitializationSegmentCache() }, video: { cache: new InitializationSegmentCache() } }); var adaptive = this.adaptive; var timings = this.timings; var video = this.video; var stream; try { stream = Stream({ url: url, keySystems: keySystems, subtitles: subtitles, timings: timings, timeFragment: timeFragment, adaptive: adaptive, pipelines: pipelines, videoElement: video, autoPlay: autoPlay, directFile: directFile }); } catch (err) { stream = defer(function () { throw err; }); } stream = stream.publish(); var segments = filterStreamByType(stream, "segment"); var manifests = filterStreamByType(stream, "manifest"); var stalled = filterStreamByType(stream, "stalled").startWith(null); var canPlay = filterStreamByType(stream, "loaded").filter(function (v) { return v === true; }); var loaded; if (directFile) { loaded = canPlay; } else { loaded = combineLatest(canPlay, filterStreamByType(segments.pluck("adaptation"), "audio"), filterStreamByType(segments.pluck("adaptation"), "video"), _.noop); } loaded = loaded.take(1); var stateChanges = loaded.map(PLAYER_LOADED).concat(combineLatest(this.playing, stalled, function (isPlaying, isStalled) { if (isStalled) return isStalled.name == "seeking" ? PLAYER_SEEKING : PLAYER_BUFFERING; if (isPlaying) return PLAYER_PLAYING; return PLAYER_PAUSED; })).changes().startWith(PLAYER_LOADING); var subscriptions = this.subscriptions = new CompositeDisposable(); var subs = [on(video, ["play", "pause"]).each(function (evt) { return _this2.playing.onNext(evt.type == "play"); }), segments.each(function (segment) { var type = segment.adaptation.type; var rep = segment.representation; var ada = segment.adaptation; _this2.reps[type] = rep; _this2.adas[type] = ada; if (type == "text") { _this2.__recordState("subtitle", ada.lang); } if (type == "video") { _this2.__recordState("videoBitrate", rep.bitrate); } if (type == "audio") { _this2.__recordState("language", ada.lang); _this2.__recordState("audioBitrate", rep.bitrate); } _this2.trigger("progress", segment); }), manifests.each(function (m) { _this2.man = m; _this2.trigger("manifestChange", m); }), stateChanges.each(function (s) { return _this2._setState(s); }), timings.each(function (t) { return _this2._triggerTimeChange(t); }), stream.subscribe(function () {}, function (e) { _this2.resetStates(); _this2.trigger("error", e); _this2._setState(PLAYER_STOPPED); _this2._clear(); }, function () { _this2.resetStates(); _this2._setState(PLAYER_ENDED); _this2._clear(); }), stream.subscribe(function (n) { return _this2.stream.onNext(n); }, function (e) { return _this2.stream.onNext({ type: "error", value: e }); }), stream.connect()]; _.each(subs, function (s) { return subscriptions.add(s); }); // _clear may have been called synchronously on early disposable if (!this.subscriptions) { subscriptions.dispose(); } this._triggerTimeChange(); return loaded.toPromise(); }; Player.prototype._setState = function _setState(s) { if (this.state !== s) { this.state = s; this.trigger("playerStateChange", s); } }; Player.prototype._triggerTimeChange = function _triggerTimeChange(t) { if (!this.man || !t) { this.trigger("currentTimeChange", getEmptyTimings()); } else { if (this.man.isLive && t.ts > 0) { t.wallClockTime = toWallClockTime(t.ts, this.man); t.liveGap = getLiveGap(t.ts, this.man); } this.trigger("currentTimeChange", t); } }; Player.prototype.getManifest = function getManifest() { return this.man; }; Player.prototype.getVideoElement = function getVideoElement() { return this.video; }; Player.prototype.getNativeTextTrack = function getNativeTextTrack() { return this.video.textTracks[0]; }; Player.prototype.getPlayerState = function getPlayerState() { return this.state; }; Player.prototype.isLive = function isLive() { assertMan(this); return this.man.isLive; }; Player.prototype.getUrl = function getUrl() { assertMan(this); return this.man.locations[0]; }; Player.prototype.getVideoDuration = function getVideoDuration() { return this.video.duration; }; Player.prototype.getVideoLoadedTime = function getVideoLoadedTime() { return new BufferedRanges(this.video.buffered).getSize(this.video.currentTime); }; Player.prototype.getVideoPlayedTime = function getVideoPlayedTime() { return new BufferedRanges(this.video.buffered).getLoaded(this.video.currentTime); }; Player.prototype.getCurrentTime = function getCurrentTime() { if (!this.man) return 0; var ct = this.video.currentTime; if (this.man.isLive) { return toWallClockTime(ct, this.man); } else { return ct; } }; Player.prototype.getStartTime = function getStartTime() { return this.frag.start; }; Player.prototype.getEndTime = function getEndTime() { return this.frag.end; }; Player.prototype.getPlaybackRate = function getPlaybackRate() { return this.video.playbackRate; }; Player.prototype.getVolume = function getVolume() { return this.video.volume; }; Player.prototype.isFullscreen = function isFullscreen() { return _isFullscreen(); }; Player.prototype.getAvailableLanguages = function getAvailableLanguages() { return this.man && manifestHelpers.getAvailableLanguages(this.man) || []; }; Player.prototype.getAvailableSubtitles = function getAvailableSubtitles() { return this.man && manifestHelpers.getAvailableSubtitles(this.man) || []; }; Player.prototype.getLanguage = function getLanguage() { return this.adaptive.getLanguage(); }; Player.prototype.getSubtitle = function getSubtitle() { return this.adaptive.getSubtitle(); }; Player.prototype.getAvailableVideoBitrates = function getAvailableVideoBitrates() { var video = manifestHelpers.getAdaptationsByType(this.man, "video"); return video[0] && video[0].bitrates || []; }; Player.prototype.getAvailableAudioBitrates = function getAvailableAudioBitrates() { var audio = this.adas.audio; return audio && audio.bitrates || []; }; Player.prototype.getVideoBitrate = function getVideoBitrate() { return this.evts.videoBitrate; }; Player.prototype.getAudioBitrate = function getAudioBitrate() { return this.evts.audioBitrate; }; Player.prototype.getVideoMaxBitrate = function getVideoMaxBitrate() { return this.adaptive.getVideoMaxBitrate(); }; Player.prototype.getAudioMaxBitrate = function getAudioMaxBitrate() { return this.adaptive.getAudioMaxBitrate(); }; Player.prototype.getVideoBufferSize = function getVideoBufferSize() { return this.adaptive.getVideoBufferSize(); }; Player.prototype.getAudioBufferSize = function getAudioBufferSize() { return this.adaptive.getAudioBufferSize(); }; Player.prototype.getAverageBitrates = function getAverageBitrates() { return this.adaptive.getAverageBitrates(); }; Player.prototype.getMetrics = function getMetrics() { return this.metrics; }; Player.prototype.getTimings = function getTimings() { return this.timings; }; Player.prototype.play = function play() { this.video.play(); }; Player.prototype.pause = function pause() { this.video.pause(); }; Player.prototype.setPlaybackRate = function setPlaybackRate(rate) { var _this3 = this; return new Promise_(function (res) { return res(_this3.video.playbackRate = rate); }); }; Player.prototype.goToStart = function goToStart() { return this.seekTo(this.getStartTime()); }; Player.prototype.seekTo = function seekTo(time) { var _this4 = this; return new Promise_(function (res) { assert(_this4.man); var currentTs = _this4.video.currentTime; if (_this4.man.isLive) time = fromWallClockTime(time, _this4.man); if (time !== currentTs) { log.info("seek to", time); res(_this4.video.currentTime = time); } else { res(currentTs); } }); }; Player.prototype.setFullscreen = function setFullscreen() { var toggle = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; if (toggle === false) exitFullscreen();else requestFullscreen(this.video); }; Player.prototype.setVolume = function setVolume(volume) { if (volume !== this.video.volume) { this.video.volume = volume; this.trigger("volumeChange", volume); } }; Player.prototype.mute = function mute() { this.muted = this.getVolume() || 0.1; this.setVolume(0); }; Player.prototype.unMute = function unMute() { var vol = this.getVolume(); if (vol === 0) this.setVolume(this.muted); }; Player.prototype.setLanguage = function setLanguage(lng) { var _this5 = this; // TODO(pierre): proper promise return new Promise_(function (res) { assert(_.contains(_this5.getAvailableLanguages(), lng), "player: unknown language"); res(_this5.adaptive.setLanguage(lng)); }); }; Player.prototype.setSubtitle = function setSubtitle(sub) { var _this6 = this; // TODO(pierre): proper promise return new Promise_(function (res) { assert(!sub || _.contains(_this6.getAvailableSubtitles(), sub), "player: unknown subtitle"); res(_this6.adaptive.setSubtitle(sub || "")); }).then(function () { if (!sub) _this6.__recordState("subtitle", null); }); }; Player.prototype.setVideoBitrate = function setVideoBitrate(btr) { var _this7 = this; // TODO(pierre): proper promise return new Promise_(function (res) { assert(btr === 0 || _.contains(_this7.getAvailableVideoBitrates(), btr), "player: video bitrate unavailable"); res(_this7.adaptive.setVideoBitrate(btr)); }); }; Player.prototype.setAudioBitrate = function setAudioBitrate(btr) { var _this8 = this; // TODO(pierre): proper promise return new Promise_(function (res) { assert(btr === 0 || _.contains(_this8.getAvailableAudioBitrates(), btr), "player: audio bitrate unavailable"); res(_this8.adaptive.setAudioBitrate(btr)); }); }; Player.prototype.setVideoMaxBitrate = function setVideoMaxBitrate(btr) { var _this9 = this; // TODO(pierre): proper promise return new Promise_(function (res) { res(_this9.adaptive.setVideoMaxBitrate(btr)); }); }; Player.prototype.setAudioMaxBitrate = function setAudioMaxBitrate(btr) { var _this10 = this; // TODO(pierre): proper promise return new Promise_(function (res) { res(_this10.adaptive.setAudioMaxBitrate(btr)); }); }; Player.prototype.setVideoBufferSize = function setVideoBufferSize(size) { var _this11 = this; // TODO(pierre): proper promise return new Promise_(function (res) { return res(_this11.adaptive.setVideoBufferSize(size)); }); }; Player.prototype.setAudioBufferSize = function setAudioBufferSize(size) { var _this12 = this; // TODO(pierre): proper promise return new Promise_(function (res) { return res(_this12.adaptive.setAudioBufferSize(size)); }); }; Player.prototype.getStreamObservable = function getStreamObservable() { return this.stream; }; Player.prototype.getDebug = function getDebug() { return debugPane.getDebug(this); }; Player.prototype.showDebug = function showDebug() { debugPane.showDebug(this, this.video); }; Player.prototype.hideDebug = function hideDebug() { debugPane.hideDebug(); }; Player.prototype.toggleDebug = function toggleDebug() { debugPane.toggleDebug(this, this.video); }; Player.prototype.getCurrentKeySystem = function getCurrentKeySystem() { return EME.getCurrentKeySystem(); }; return Player; })(EventEmitter); module.exports = Player; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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) : subClass.__proto__ = superClass; } var EventEmitter = __webpack_require__(10); var _require = __webpack_require__(9); var BufferedRanges = _require.BufferedRanges; var Promise_ = __webpack_require__(6); var assert = __webpack_require__(2); var AbstractSourceBuffer = (function (_EventEmitter) { _inherits(AbstractSourceBuffer, _EventEmitter); function AbstractSourceBuffer(codec) { _classCallCheck(this, AbstractSourceBuffer); _EventEmitter.call(this); this.codec = codec; this.updating = false; this.readyState = "opened"; this.buffered = new BufferedRanges(); } AbstractSourceBuffer.prototype.appendBuffer = function appendBuffer(data) { var _this = this; return this._lock(function () { return _this._append(data); }); }; AbstractSourceBuffer.prototype.remove = function remove(from, to) { var _this2 = this; return this._lock(function () { return _this2._remove(from, to); }); }; AbstractSourceBuffer.prototype.abort = function abort() { this.remove(0, Infinity); this.updating = false; this.readyState = "closed"; this._abort(); }; AbstractSourceBuffer.prototype._append = function _append() /* data */{}; AbstractSourceBuffer.prototype._remove = function _remove() /* from, to */{}; AbstractSourceBuffer.prototype._abort = function _abort() {}; AbstractSourceBuffer.prototype._lock = function _lock(func) { var _this3 = this; assert(!this.updating, "text-buffer: cannot remove while updating"); this.updating = true; this.trigger("updatestart"); return new Promise_(function (res) { return res(func()); }).then(function () { return _this3._unlock("update"); }, function (e) { return _this3._unlock("error", e); }); }; AbstractSourceBuffer.prototype._unlock = function _unlock(eventName, value) { this.trigger(eventName, value); this.updating = false; this.trigger("updateend"); }; return AbstractSourceBuffer; })(EventEmitter); module.exports = AbstractSourceBuffer; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var log = __webpack_require__(4); var assert = __webpack_require__(2); var _require = __webpack_require__(3); var Observable = _require.Observable; var _require2 = __webpack_require__(5); var first = _require2.first; var on = _require2.on; var _require3 = __webpack_require__(19); var getLiveGap = _require3.getLiveGap; var seekingsSampler = _require3.seekingsSampler; var fromWallClockTime = _require3.fromWallClockTime; var _require4 = __webpack_require__(5); var retryWithBackoff = _require4.retryWithBackoff; var empty = Observable.empty; var never = Observable.never; var just = Observable.just; var merge = Observable.merge; var combineLatest = Observable.combineLatest; var min = Math.min; var _require5 = __webpack_require__(8); var MediaSource_ = _require5.MediaSource_; var sourceOpen = _require5.sourceOpen; var canPlay = _require5.canPlay; var loadedMetadata = _require5.loadedMetadata; var TextSourceBuffer = __webpack_require__(35); var _require6 = __webpack_require__(17); var getLiveEdge = _require6.getLiveEdge; var Buffer = __webpack_require__(25); var EME = __webpack_require__(16); var _require7 = __webpack_require__(12); var normalizeManifest = _require7.normalizeManifest; var mergeManifestsIndex = _require7.mergeManifestsIndex; var mutateManifestLiveGap = _require7.mutateManifestLiveGap; var getAdaptations = _require7.getAdaptations; var END_OF_PLAY = 0.2; var TOTAL_RETRY_COUNT = 3; // discontinuity threshold in seconds var DISCONTINUITY_THRESHOLD = 1; function plugDirectFile(url, video) { return Observable.create(function (observer) { video.src = url; observer.onNext({ url: url }); return function () { video.src = ""; }; }); } function isNativeBuffer(bufferType) { return bufferType == "audio" || bufferType == "video"; } function Stream(_ref) { var url = _ref.url; var keySystems = _ref.keySystems; var subtitles = _ref.subtitles; var timings = _ref.timings; var timeFragment = _ref.timeFragment; var adaptive = _ref.adaptive; var pipelines = _ref.pipelines; var videoElement = _ref.videoElement; var autoPlay = _ref.autoPlay; var directFile = _ref.directFile; assert(MediaSource_, "player: browser is required to support MediaSource"); var fragStartTime = timeFragment.start; var fragEndTime = timeFragment.end; var fragEndTimeIsFinite = fragEndTime < Infinity; var manifestPipeline = pipelines.manifest; var nativeBuffers = {}; var customBuffers = {}; function createSourceBuffer(video, mediaSource, bufferInfos) { var type = bufferInfos.type; var codec = bufferInfos.codec; var sourceBuffer; if (isNativeBuffer(type)) { if (nativeBuffers[type]) { sourceBuffer = nativeBuffers[type]; } else { log.info("add sourcebuffer", codec); sourceBuffer = mediaSource.addSourceBuffer(codec); nativeBuffers[type] = sourceBuffer; } } else { var oldSourceBuffer = customBuffers[type]; if (oldSourceBuffer) { try { oldSourceBuffer.abort(); } catch (e) { log.warn(e); } finally { delete customBuffers[type]; } } if (type == "text") { log.info("add text sourcebuffer", codec); sourceBuffer = new TextSourceBuffer(video, codec); } // else if (type == "image") { // ... // } else { var errMessage = "stream: unknown buffer type " + type; log.error(errMessage); throw new Error(errMessage); } customBuffers[type] = sourceBuffer; } return sourceBuffer; } function disposeSourceBuffer(video, mediaSource, bufferInfos) { var type = bufferInfos.type; var oldSourceBuffer; var isNative = isNativeBuffer(type); if (isNative) { oldSourceBuffer = nativeBuffers[type]; delete nativeBuffers[type]; } else { oldSourceBuffer = customBuffers[type]; delete customBuffers[type]; } if (oldSourceBuffer) { try { oldSourceBuffer.abort(); if (isNative) mediaSource.removeSourceBuffer(oldSourceBuffer); } catch (e) { log.warn(e); } } } function createAndPlugMediaSource(url, video) { return Observable.create(function (observer) { var mediaSource = new MediaSource_(); var objectURL = video.src = URL.createObjectURL(mediaSource); observer.onNext({ url: url, mediaSource: mediaSource }); log.info("create mediasource object", objectURL); return function () { if (mediaSource && mediaSource.readyState != "closed") { var state = mediaSource.readyState; _.each(_.cloneArray(mediaSource.sourceBuffers), function (sourceBuffer) { try { if (state == "open") sourceBuffer.abort(); mediaSource.removeSourceBuffer(sourceBuffer); } catch (e) { log.warn("error while disposing souceBuffer", e); } }); } _.each(_.keys(customBuffers), function (sourceBufferType) { var sourceBuffer = customBuffers[sourceBufferType]; try { sourceBuffer.abort(); } catch (e) { log.warn("error while disposing souceBuffer", e); } }); // clear video srcAttribute video.src = ""; if (objectURL) { try { URL.revokeObjectURL(objectURL); } catch (e) { log.warn("error while revoking ObjectURL", e); } } nativeBuffers = null; customBuffers = null; mediaSource = null; objectURL = null; }; }); } function createTimings(manifest) { var augmentedTimings = timings.map(function (timing) { var clonedTiming; if (fragEndTimeIsFinite) { clonedTiming = _.cloneObject(timing); clonedTiming.ts = min(timing.ts, fragEndTime); clonedTiming.duration = min(timing.duration, fragEndTime); } else { clonedTiming = timing; } clonedTiming.liveGap = getLiveGap(timing.ts, manifest); return clonedTiming; }); var seekings = seekingsSampler(augmentedTimings); return { timings: augmentedTimings, seekings: seekings }; } /** * End-Of-Play stream popping a value when timings reaches the end of the * video */ var endOfPlay = timings.filter(function (_ref2) { var ts = _ref2.ts; var duration = _ref2.duration; return duration > 0 && min(duration, fragEndTime) - ts < END_OF_PLAY; }).take(1).share(); if (directFile) { return plugDirectFile(url, videoElement).flatMap(createDirectFileStream).takeUntil(endOfPlay); } /** * Wait for manifest and media-source to open before initializing source * duration and creating buffers */ var createAllStream = retryWithBackoff(function (_ref3) { var url = _ref3.url; var mediaSource = _ref3.mediaSource; var sourceOpening = sourceOpen(mediaSource); return manifestPipeline({ url: url }).zip(sourceOpening, _.identity).flatMap(function (_ref4) { var parsed = _ref4.parsed; var manifest = normalizeManifest(parsed.url, parsed.manifest, subtitles); setDuration(mediaSource, manifest); return createStream(mediaSource, manifest); }); }, { retryDelay: 500, totalRetry: TOTAL_RETRY_COUNT, resetDelay: 60 * 1000, shouldRetry: function shouldRetry(err, tryCount) { if (/MEDIA_ERR/.test(err.message)) { return false; } else { log.warn("stream retry", err, tryCount); return true; } } }); return createAndPlugMediaSource(url, videoElement).flatMap(createAllStream).takeUntil(endOfPlay); /** * Creates a stream of audio/video/text buffers given a set of * adaptations and a codec information. * * For each buffer stream, a unique "sourceBuffer" observable is * created that will be reused for each created buffer. * * An "adaptations choice" observable is also created and * responsible for changing the video or audio adaptation choice in * reaction to user choices (ie. changing the language). */ function createBuffer(mediaSource, bufferInfos, timings, seekings) { var type = bufferInfos.type; var adaptations = adaptive.getAdaptationsChoice(type, bufferInfos.adaptations); if (false) assert(pipelines[type], "stream: no pipeline found for type " + type); return adaptations.flatMapLatest(function (adaptation) { if (!adaptation) { disposeSourceBuffer(videoElement, mediaSource, bufferInfos); return never(); } var adapters = adaptive.getBufferAdapters(adaptation); var buffer = Buffer({ sourceBuffer: createSourceBuffer(videoElement, mediaSource, bufferInfos), pipeline: pipelines[type], adaptation: adaptation, timings: timings, seekings: seekings, adapters: adapters }); // non native buffer should not impact on the stability of the // player. ie: if a text buffer sends an error, we want to // continue streaming without any subtitles if (!isNativeBuffer(type)) { return buffer["catch"](function (err) { log.error("buffer", type, "has crashed", err); return empty(); }); } return buffer; }); } /** * Creates a stream waiting for the "loadedmetadata" and "canplay" * events. * * This stream also the side effect of setting the initial time as soon as * the loadedmetadata event pops up. */ function createLoadedMetadata(manifest) { var loadedMetadata$ = loadedMetadata(videoElement).tap(function () { return setInitialTime(manifest); }); var canPlay$ = canPlay(videoElement).tap(function () { log.info("canplay event"); if (autoPlay) videoElement.play(); autoPlay = true; }); return first(combineLatest(loadedMetadata$, canPlay$, _.noop)).map({ type: "loaded", value: true }).startWith({ type: "loaded", value: false }); } function createEME() { if (keySystems && keySystems.length) { return EME(videoElement, keySystems); } else { return EME.onEncrypted(videoElement).map(function () { var errMessage = "eme: ciphered media and no keySystem passed"; log.error(errMessage); throw new Error(errMessage); }); } } /** * Extracted stalled info changing over-time from timings. This * stream has a side-effect of the <video> playbackRate property. * * It mutates its value to stop the video when buffer is too low, or * resume the video when the buffer has regained a decent size. */ function createStalled(timings) { var changePlaybackRate = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1]; return timings.distinctUntilChanged(null, function (prevTiming, timing) { var isStalled = timing.stalled; var wasStalled = prevTiming.stalled; var isEqual; if (!wasStalled && !isStalled) isEqual = true;else if (!wasStalled || !isStalled) isEqual = false;else isEqual = wasStalled.name == isStalled.name; if (!isEqual && changePlaybackRate) { if (wasStalled) { log.info("resume playback", timing.ts, timing.name); videoElement.playbackRate = wasStalled.playback; } else { log.info("stop playback", timing.ts, timing.name); videoElement.playbackRate = 0; } } // Discontinuity check in case we are close a buffer but still // calculate a stalled state. This is useful for some // implementation that might drop an injected segment, or in // case of small discontinuity in the stream. if (isStalled) { var nextRangeGap = timing.buffered.getNextRangeGap(timing.ts); if (nextRangeGap < DISCONTINUITY_THRESHOLD) { var seekTo = timing.ts + nextRangeGap + 1 / 60; videoElement.currentTime = seekTo; log.warn("discontinuity seek", timing.ts, nextRangeGap, seekTo); } } return isEqual; }).map(function (timing) { return { type: "stalled", value: timing.stalled }; }); } function isOutOfIndexError(err) { return err && err.type == "out-of-index"; } function isPreconditionFailedError(err) { return err && err.type == "precondition-failed"; } function manifestAdapter(manifest, message) { // out-of-index messages require a complete reloading of the // manifest to refresh the current index if (isOutOfIndexError(message)) { log.info("out of index"); return manifestPipeline({ url: manifest.locations[0] }).map(function (_ref5) { var parsed = _ref5.parsed; var newManifest = mergeManifestsIndex(manifest, normalizeManifest(parsed.url, parsed.manifest, subtitles)); return { type: "manifest", value: newManifest }; }); } // precondition-failed messages require a change of live-gap to // calibrate the live representation of the player // TODO(pierre): smarter converging algorithm if (isPreconditionFailedError(message)) { mutateManifestLiveGap(manifest, 1); log.warn("precondition failed", manifest.presentationLiveGap); } return just(message); } function createAdaptationsBuffers(mediaSource, manifest, timings, seekings) { var adaptationsBuffers = _.map(getAdaptations(manifest), function (adaptation) { return createBuffer(mediaSource, adaptation, timings, seekings); }); var buffers = merge(adaptationsBuffers); if (!manifest.isLive) return buffers; // handle manifest reloading for live streamings using outofindex // errors thrown when a buffer asks for a segment out of its // current index return buffers // do not throw multiple times OutOfIndexErrors in order to have // only one manifest reload for each error. .distinctUntilChanged(null, function (a, b) { return isOutOfIndexError(b) && isOutOfIndexError(a); }).concatMap(function (message) { return manifestAdapter(manifest, message); }); } /** * Creates a stream merging all observable that are required to make * the system cooperate. */ function createStream(mediaSource, manifest) { var _createTimings = createTimings(manifest); var timings = _createTimings.timings; var seekings = _createTimings.seekings; var justManifest = just({ type: "manifest", value: manifest }); var canPlay = createLoadedMetadata(manifest); var buffers = createAdaptationsBuffers(mediaSource, manifest, timings, seekings); var emeHandler = createEME(); var stalled = createStalled(timings, true); var mediaError = on(videoElement, "error").flatMap(function () { var errMessage = "stream: video element MEDIA_ERR code " + videoElement.error.code; log.error(errMessage); throw new Error(errMessage); }); return merge(justManifest, canPlay, emeHandler, buffers, stalled, mediaError); } function createDirectFileStream() { var _createTimings2 = createTimings(directFile, { timeInterval: 1000 }); var timings = _createTimings2.timings; var justManifest = just({ type: "manifest", value: directFile }); var canPlay = createLoadedMetadata(directFile); var stalled = createStalled(timings, false); return merge(justManifest, canPlay, stalled); } /** * Side effect the set the media duration in mediaSource. This side * effect occurs when we receive the "sourceopen" from the * mediaSource. */ function setDuration(mediaSource, manifest) { if (manifest.duration === Infinity) { // TODO(pierre): hack for Chrome 42 mediaSource.duration = Number.MAX_VALUE; } else { mediaSource.duration = manifest.duration; } log.info("set duration", mediaSource.duration); } /** * Side effect to set the initial time of the video: * - if a start time is defined by user, set it as start time * - if video is live, use the live edge * - else set the start time to 0 * * This side effect occurs when we receive the "loadedmetadata" event from * the <video>. * * see: createLoadedMetadata(manifest) */ function setInitialTime(manifest) { var duration = manifest.duration; var startTime = fragStartTime; var endTime = fragEndTime; var percentage = /^\d*(\.\d+)? ?%$/; if (_.isString(startTime) && percentage.test(startTime)) { startTime = parseFloat(startTime) / 100 * duration; } if (_.isString(endTime) && percentage.test(endTime)) { fragEndTime = parseFloat(endTime) / 100 * duration; } if (endTime === Infinity || endTime === "100%") endTime = duration; if (!manifest.isLive) { assert(startTime < duration && endTime <= duration, "stream: bad startTime and endTime"); } else if (startTime) { startTime = fromWallClockTime(startTime, manifest); } else { startTime = getLiveEdge(manifest); } log.info("set initial time", startTime); videoElement.currentTime = startTime; } } module.exports = Stream; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; 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) : subClass.__proto__ = superClass; } var Promise_ = __webpack_require__(6); var _ = __webpack_require__(1); var AbstractSourceBuffer = __webpack_require__(33); var Cue = window.VTTCue || window.TextTrackCue; var TextSourceBuffer = (function (_AbstractSourceBuffer) { _inherits(TextSourceBuffer, _AbstractSourceBuffer); function TextSourceBuffer(video, codec) { _classCallCheck(this, TextSourceBuffer); _AbstractSourceBuffer.call(this, codec); this.video = video; this.codec = codec; this.isVTT = /^text\/vtt/.test(codec); // there is no removeTextTrack method... so we need to reuse old // text-tracks objects and clean all its pending cues var trackElement = document.createElement("track"); var track = trackElement.track; this.trackElement = trackElement; this.track = track; trackElement.kind = "subtitles"; track.mode = "showing"; video.appendChild(trackElement); } TextSourceBuffer.prototype.createCuesFromArray = function createCuesFromArray(cues) { if (!cues.length) return []; return _.compact(_.map(cues, function (_ref) { var start = _ref.start; var end = _ref.end; var text = _ref.text; if (text) return new Cue(start, end, text); })); }; TextSourceBuffer.prototype._append = function _append(cues) { var _this = this; if (this.isVTT) { var blob = new Blob([cues], { type: "text/vtt" }); var url = URL.createObjectURL(blob); this.trackElement.src = url; this.buffered.insert(0, Infinity); } else { var trackCues = this.createCuesFromArray(cues); if (trackCues.length) { _.each(trackCues, function (cue) { return _this.track.addCue(cue); }); var firstCue = trackCues[0]; var lastCue = _.last(trackCues); this.buffered.insert(0, firstCue.startTime, lastCue.endTime); } } return Promise_.resolve(); }; TextSourceBuffer.prototype._remove = function _remove(from, to) { var track = this.track; _.each(_.cloneArray(track.cues), function (cue) { var startTime = cue.startTime; var endTime = cue.endTime; if (startTime >= from && startTime <= to && endTime <= to) { track.removeCue(cue); } }); }; TextSourceBuffer.prototype._abort = function _abort() { var trackElement = this.trackElement; var video = this.video; if (trackElement && video && video.hasChildNodes(trackElement)) { video.removeChild(trackElement); } this.track.mode = "disabled"; this.size = 0; this.trackElement = null; this.track = null; this.video = null; }; return TextSourceBuffer; })(AbstractSourceBuffer); module.exports = TextSourceBuffer; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var assert = __webpack_require__(2); function parseTimeFragment(timeFragment) { if (_.isString(timeFragment)) { timeFragment = temporalMediaFragmentParser(timeFragment); } else { timeFragment = _.pick(timeFragment, ["start", "end"]); } if (_.isString(timeFragment.start) && _.isString(timeFragment.end)) { if (!timeFragment.start) timeFragment.start = "0%"; if (!timeFragment.end) timeFragment.end = "100%"; } else { if (!timeFragment.start) timeFragment.start = 0; if (!timeFragment.end) timeFragment.end = Infinity; } if (_.isString(timeFragment.start) && _.isString(timeFragment.end)) { assert(parseFloat(timeFragment.start) >= 0 && parseFloat(timeFragment.start) <= 100, "player: startTime should be between 0% and 100%"); assert(parseFloat(timeFragment.end) >= 0 && parseFloat(timeFragment.end) <= 100, "player: endTime should be between 0% and 100%"); } else { assert((_.isNumber(timeFragment.start) || _.isDate(timeFragment.start)) && (_.isNumber(timeFragment.end) || _.isDate(timeFragment.end)), "player: timeFragment should have interface { start, end } where start and end are numbers or dates"); assert(timeFragment.start < timeFragment.end, "player: startTime should be lower than endTime"); assert(timeFragment.start >= 0, "player: startTime should be greater than 0"); } return timeFragment; } var errMessage = "Invalid MediaFragment"; function normalizeNTPTime(time) { if (!time) return false; // replace a sole trailing dot, which is legal: // npt-sec = 1*DIGIT [ "." *DIGIT ] time = time.replace(/^npt\:/, "").replace(/\.$/, ""); // possible cases: // 12:34:56.789 // 34:56.789 // 56.789 // 56 var hours; var minutes; var seconds; time = time.split(":"); var length = time.length; switch (length) { case 3: hours = parseInt(time[0], 10); minutes = parseInt(time[1], 10); seconds = parseFloat(time[2]); break; case 2: hours = 0; minutes = parseInt(time[0], 10); seconds = parseFloat(time[1]); break; case 1: hours = 0; minutes = 0; seconds = parseFloat(time[0]); break; default: return false; } assert(hours <= 23, errMessage); assert(minutes <= 59, errMessage); assert(length <= 1 || seconds < 60, errMessage); return hours * 3600 + minutes * 60 + seconds; } // we interpret frames as milliseconds, and further-subdivison-of-frames // as microseconds. this allows for relatively easy comparison. function normalizeSMPTETime(time) { if (!time) return false; // possible cases: // 12:34:56 // 12:34:56:78 // 12:34:56:78.90 var hours; var minutes; var seconds; var frames; var subframes; time = time.split(":"); var length = time.length; switch (length) { case 3: hours = parseInt(time[0], 10); minutes = parseInt(time[1], 10); seconds = parseInt(time[2], 10); frames = 0; subframes = 0; break; case 4: hours = parseInt(time[0], 10); minutes = parseInt(time[1], 10); seconds = parseInt(time[2], 10); if (time[3].indexOf(".") === -1) { frames = parseInt(time[3], 10); subframes = 0; } else { var frameSubFrame = time[3].split("."); frames = parseInt(frameSubFrame[0], 10); subframes = parseInt(frameSubFrame[1], 10); } break; default: return false; } assert(hours <= 23, errMessage); assert(minutes <= 59, errMessage); assert(seconds <= 59, errMessage); return hours * 3600 + minutes * 60 + seconds + frames * 0.001 + subframes * 0.000001; } function normalizeWallClockTime(time) { return new Date(Date.parse(time)); } function normalizePercentage(time) { if (!time) return false; return time; } // MediaFragment temporal parser. // adapted from: https://github.com/tomayac/Media-Fragments-URI // specification: http://www.w3.org/TR/media-frags/#naming-time function temporalMediaFragmentParser(value) { var components = value.split(","); assert(components.length <= 2, errMessage); var start = components[0] ? components[0] : ""; var end = components[1] ? components[1] : ""; assert((start || end) && (!start || end || value.indexOf(",") === -1), errMessage); start = start.replace(/^smpte(-25|-30|-30-drop)?\:/, "").replace("clock:", ""); // hours:minutes:seconds.milliseconds var npt = /^((npt\:)?((\d+\:(\d\d)\:(\d\d))|((\d\d)\:(\d\d))|(\d+))(\.\d*)?)?$/; // hours:minutes:seconds:frames.further-subdivison-of-frames var smpte = /^(\d+\:\d\d\:\d\d(\:\d\d(\.\d\d)?)?)?$/; // regexp adapted from http://delete.me.uk/2005/03/iso8601.html var wallClock = /^((\d{4})(-(\d{2})(-(\d{2})(T(\d{2})\:(\d{2})(\:(\d{2})(\.(\d+))?)?(Z|(([-\+])(\d{2})\:(\d{2})))?)?)?)?)?$/; // float% var percentage = /^(\d*(\.\d+)? ?%)?$/; var timeNormalizer; if (npt.test(start) && npt.test(end)) { timeNormalizer = normalizeNTPTime; } else if (smpte.test(start) && smpte.test(end)) { timeNormalizer = normalizeSMPTETime; } else if (wallClock.test(start) && wallClock.test(end)) { timeNormalizer = normalizeWallClockTime; } else if (percentage.test(start) && percentage.test(end)) { timeNormalizer = normalizePercentage; } else { throw new Error(errMessage); } start = timeNormalizer(start); end = timeNormalizer(end); assert(start !== false || end !== false, errMessage); return { start: start === false ? "" : start, end: end === false ? "" : end }; } module.exports = { parseTimeFragment: parseTimeFragment }; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var _require = __webpack_require__(3); var Observable = _require.Observable; var empty = Observable.empty; var merge = Observable.merge; var just = Observable.just; var assert = __webpack_require__(2); var request = __webpack_require__(14); var _require2 = __webpack_require__(11); var resolveURL = _require2.resolveURL; var _require3 = __webpack_require__(38); var parseSidx = _require3.parseSidx; var patchPssh = _require3.patchPssh; var dashManifestParser = __webpack_require__(39); function byteRange(_ref) { var start = _ref[0]; var end = _ref[1]; if (!end || end === Infinity) { return "bytes=" + +start + "-"; } else { return "bytes=" + +start + "-" + +end; } } function replaceTokens(path, representation, time, number) { if (path.indexOf("$") === -1) { return path; } else { return path.replace(/\$\$/g, "$").replace(/\$RepresentationID\$/g, representation.id).replace(/\$Bandwidth\$/g, representation.bitrate).replace(/\$Number\$/g, number).replace(/\$Time\$/g, time); } } function createURL(adaptation, representation, path) { return resolveURL(adaptation.rootURL, adaptation.baseURL, representation.baseURL, path); } var req = function req(reqOptions) { reqOptions.withMetadata = true; return request(reqOptions); }; module.exports = function () { var opts = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var contentProtectionParser = opts.contentProtectionParser; if (!contentProtectionParser) contentProtectionParser = _.noop; var manifestPipeline = { loader: function loader(_ref2) { var url = _ref2.url; return req({ url: url, format: "document" }); }, parser: function parser(_ref3) { var response = _ref3.response; return just({ manifest: dashManifestParser(response.blob, contentProtectionParser), url: response.url }); } }; var segmentPipeline = { loader: function loader(_ref4) { var adaptation = _ref4.adaptation; var representation = _ref4.representation; var segment = _ref4.segment; var init = segment.init; var media = segment.media; var range = segment.range; var indexRange = segment.indexRange; // init segment without initialization media/range/indexRange: // we do nothing on the network if (init && !(media || range || indexRange)) { return empty(); } var mediaHeaders; if (_.isArray(range)) { mediaHeaders = { "Range": byteRange(range) }; } else { mediaHeaders = null; } var path; if (media) { path = replaceTokens(media, representation, segment.time, segment.number); } else { path = ""; } var mediaUrl = createURL(adaptation, representation, path); var mediaOrInitRequest = req({ url: mediaUrl, format: "arraybuffer", headers: mediaHeaders }); // If init segment has indexRange metadata, we need to fetch // both the initialization data and the index metadata. We do // this in parallel and send the both blobs into the pipeline. // TODO(pierre): we could fire both these requests as one if the // init and index ranges are contiguous, which should be the // case most of the time. if (_.isArray(indexRange)) { var indexRequest = req({ url: mediaUrl, format: "arraybuffer", headers: { "Range": byteRange(indexRange) } }); return merge(mediaOrInitRequest, indexRequest); } else { return mediaOrInitRequest; } }, parser: function parser(_ref5) { var adaptation = _ref5.adaptation; var segment = _ref5.segment; var response = _ref5.response; var blob = new Uint8Array(response.blob); var init = segment.init; var indexRange = segment.indexRange; // added segments and timescale informations are extracted from // sidx atom var nextSegments, timescale, currentSegment; // added index (segments and timescale) informations are // extracted from sidx atom var index = parseSidx(blob, indexRange ? indexRange[0] : 0); if (index) { nextSegments = index.segments; timescale = index.timescale; } if (!init) { // current segment information may originate from the index // itself in which case we don't have to use the index // segments. if (segment.time >= 0 && segment.duration >= 0) { currentSegment = { ts: segment.time, d: segment.duration }; } else if (index && index.segments.length === 1) { currentSegment = { ts: index.segments[0].ts, d: index.segments[0].d }; } if (false) assert(currentSegment); } if (init && adaptation.contentProtection) { blob = patchPssh(blob, adaptation.contentProtection); } return just({ blob: blob, currentSegment: currentSegment, nextSegments: nextSegments, timescale: timescale }); } }; var textTrackPipeline = { loader: function loader() /* { adaptation, representation, segment } */{} }; return { manifest: manifestPipeline, audio: segmentPipeline, video: segmentPipeline, text: textTrackPipeline }; }; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var assert = __webpack_require__(2); var _require = __webpack_require__(7); var itobe4 = _require.itobe4; var be8toi = _require.be8toi; var be4toi = _require.be4toi; var be2toi = _require.be2toi; var hexToBytes = _require.hexToBytes; var strToBytes = _require.strToBytes; var concat = _require.concat; function findAtom(buf, atomName) { var i = 0, l = buf.length; var name, size; while (i + 8 < l) { size = be4toi(buf, i); name = be4toi(buf, i + 4); assert(size > 0, "dash: out of range size"); if (name === atomName) { break; } else { i += size; } } if (i >= l) return -1; assert(i + size <= l, "dash: atom out of range"); return i; } function parseSidx(buf, offset) { var index = findAtom(buf, 0x73696478 /* "sidx" */); if (index == -1) return null; var size = be4toi(buf, index); var pos = index + /* size */4 + /* name */4; /* version(8) */ /* flags(24) */ /* reference_ID(32); */ /* timescale(32); */ var version = buf[pos];pos += 4 + 4; var timescale = be4toi(buf, pos);pos += 4; /* earliest_presentation_time(32 / 64) */ /* first_offset(32 / 64) */ var time; if (version === 0) { time = be4toi(buf, pos);pos += 4; offset += be4toi(buf, pos) + size;pos += 4; } else if (version === 1) { time = be8toi(buf, pos);pos += 8; offset += be8toi(buf, pos) + size;pos += 8; } else { return null; } var segments = []; /* reserved(16) */ /* reference_count(16) */ pos += 2; var count = be2toi(buf, pos); pos += 2; while (--count >= 0) { /* reference_type(1) */ /* reference_size(31) */ /* segment_duration(32) */ /* sap..(32) */ var refChunk = be4toi(buf, pos); pos += 4; var refType = (refChunk & 0x80000000) >>> 31; var refSize = refChunk & 0x7fffffff; if (refType == 1) throw new Error("not implemented"); var d = be4toi(buf, pos); pos += 4; // var sapChunk = be4toi(buf, pos + 8); pos += 4; // TODO(pierre): handle sap // var startsWithSap = (sapChunk & 0x80000000) >>> 31; // var sapType = (sapChunk & 0x70000000) >>> 28; // var sapDelta = sapChunk & 0x0FFFFFFF; var ts = time; segments.push({ ts: ts, d: d, r: 0, range: [offset, offset + refSize - 1] }); time += d; offset += refSize; } return { segments: segments, timescale: timescale }; } function Atom(name, buff) { var len = buff.length + 8; return concat(itobe4(len), strToBytes(name), buff); } function createPssh(_ref) { var systemId = _ref.systemId; var privateData = _ref.privateData; systemId = systemId.replace(/-/g, ""); assert(systemId.length === 32); return Atom("pssh", concat(4, hexToBytes(systemId), itobe4(privateData.length), privateData)); } function patchPssh(buf, pssList) { if (!pssList || !pssList.length) return buf; var pos = findAtom(buf, 0x6d6f6f76 /* = "moov" */); if (pos == -1) return buf; var size = be4toi(buf, pos); var moov = buf.subarray(pos, pos + size); var newmoov = [moov]; for (var i = 0; i < pssList.length; i++) { newmoov.push(createPssh(pssList[i])); } newmoov = concat.apply(null, newmoov); newmoov.set(itobe4(newmoov.length), 0); return concat(buf.subarray(0, pos), newmoov, buf.subarray(pos + size)); } module.exports = { parseSidx: parseSidx, patchPssh: patchPssh }; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // XML-Schema // <http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd> "use strict"; var _ = __webpack_require__(1); var assert = __webpack_require__(2); var iso8601Duration = /^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/; var rangeRe = /([0-9]+)-([0-9]+)/; var frameRateRe = /([0-9]+)(\/([0-9]+))?/; // TODO(pierre): support more than juste timeline index type function calcLastRef(index) { var _$last = _.last(index.timeline); var ts = _$last.ts; var r = _$last.r; var d = _$last.d; return (ts + (r + 1) * d) / index.timescale; } function feedAttributes(node, base) { var attrs = attributes[node.nodeName]; assert(attrs, "parser: no attributes for " + node.nodeName); return _.reduce(attrs, function (obj, _ref) { var k = _ref.k; var fn = _ref.fn; var n = _ref.n; var def = _ref.def; if (node.hasAttribute(k)) { obj[n || k] = fn(node.getAttribute(k)); } else if (def != null) { obj[n || k] = def; } return obj; }, base || {}); } function parseString(str) { return str; } function parseBoolean(str) { return str == "true"; } function parseIntOrBoolean(str) { if (str == "true") return true; if (str == "false") return false; return parseInt(str); } function parseDateTime(str) { return new Date(Date.parse(str)); } function parseDuration(date) { if (!date) return 0; var match = iso8601Duration.exec(date); assert(match, "parser: " + date + " is not a valid ISO8601 duration"); return parseFloat(match[2] || 0) * 365 * 24 * 60 * 60 + parseFloat(match[4] || 0) * 30 * 24 * 60 * 60 + // not precise + parseFloat(match[6] || 0) * 24 * 60 * 60 + parseFloat(match[8] || 0) * 60 * 60 + parseFloat(match[10] || 0) * 60 + parseFloat(match[12] || 0); } function parseFrameRate(str) { var match = frameRateRe.exec(str); if (!match) return -1; var nom = parseInt(match[1]) || 0; var den = parseInt(match[2]) || 0; return den > 0 ? nom / den : nom; } function parseRatio(str) { return str; } function parseByteRange(str) { var match = rangeRe.exec(str); if (!match) return null;else return [+match[1], +match[2]]; } var RepresentationBaseType = [{ k: "profiles", fn: parseString }, { k: "width", fn: parseInt }, { k: "height", fn: parseInt }, { k: "frameRate", fn: parseFrameRate }, { k: "audioSamplingRate", fn: parseString }, { k: "mimeType", fn: parseString }, { k: "segmentProfiles", fn: parseString }, { k: "codecs", fn: parseString }, { k: "maximumSAPPeriod", fn: parseFloat }, { k: "maxPlayoutRate", fn: parseFloat }, { k: "codingDependency", fn: parseBoolean }]; var SegmentBaseType = [{ k: "timescale", fn: parseInt }, { k: "presentationTimeOffset", fn: parseFloat, def: 0 }, { k: "indexRange", fn: parseByteRange }, { k: "indexRangeExact", fn: parseBoolean }, { k: "availabilityTimeOffset", fn: parseFloat }, { k: "availabilityTimeComplete", fn: parseBoolean }]; var MultipleSegmentBaseType = SegmentBaseType.concat([{ k: "duration", fn: parseInt }, { k: "startNumber", fn: parseInt }]); var attributes = { "ContentProtection": [{ k: "schemeIdUri", fn: parseString }, { k: "value", fn: parseString }], "SegmentURL": [{ k: "media", fn: parseString }, { k: "mediaRange", fn: parseByteRange }, { k: "index", fn: parseString }, { k: "indexRange", fn: parseByteRange }], "S": [{ k: "t", fn: parseInt, n: "ts" }, { k: "d", fn: parseInt }, { k: "r", fn: parseInt }], "SegmentTimeline": [], "SegmentBase": SegmentBaseType, "SegmentTemplate": MultipleSegmentBaseType.concat([{ k: "initialization", fn: parseInitializationAttribute }, { k: "index", fn: parseString }, { k: "media", fn: parseString }, { k: "bitstreamSwitching", fn: parseString }]), "SegmentList": MultipleSegmentBaseType, "ContentComponent": [{ k: "id", fn: parseString }, { k: "lang", fn: parseString }, { k: "contentType", fn: parseString }, { k: "par", fn: parseRatio }], "Representation": RepresentationBaseType.concat([{ k: "id", fn: parseString }, { k: "bandwidth", fn: parseInt, n: "bitrate" }, { k: "qualityRanking", fn: parseInt }]), "AdaptationSet": RepresentationBaseType.concat([{ k: "id", fn: parseString }, { k: "group", fn: parseInt }, { k: "lang", fn: parseString }, { k: "contentType", fn: parseString }, { k: "par", fn: parseRatio }, { k: "minBandwidth", fn: parseInt, n: "minBitrate" }, { k: "maxBandwidth", fn: parseInt, n: "maxBitrate" }, { k: "minWidth", fn: parseInt }, { k: "maxWidth", fn: parseInt }, { k: "minHeight", fn: parseInt }, { k: "maxHeight", fn: parseInt }, { k: "minFrameRate", fn: parseFrameRate }, { k: "maxFrameRate", fn: parseFrameRate }, { k: "segmentAlignment", fn: parseIntOrBoolean }, { k: "subsegmentAlignment", fn: parseIntOrBoolean }, { k: "bitstreamSwitching", fn: parseBoolean }]), "Period": [{ k: "id", fn: parseString }, { k: "start", fn: parseDuration }, { k: "duration", fn: parseDuration }, { k: "bitstreamSwitching", fn: parseBoolean }], "MPD": [{ k: "id", fn: parseString }, { k: "profiles", fn: parseString }, { k: "type", fn: parseString }, { k: "availabilityStartTime", fn: parseDateTime }, { k: "availabilityEndTime", fn: parseDateTime }, { k: "publishTime", fn: parseDateTime }, { k: "mediaPresentationDuration", fn: parseDuration, n: "duration" }, { k: "minimumUpdatePeriod", fn: parseDuration }, { k: "minBufferTime", fn: parseDuration }, { k: "timeShiftBufferDepth", fn: parseDuration }, { k: "suggestedPresentationDelay", fn: parseDuration }, { k: "maxSegmentDuration", fn: parseDuration }, { k: "maxSubsegmentDuration", fn: parseDuration }] }; function reduceChildren(root, fn, init) { var node = root.firstElementChild, r = init; while (node) { r = fn(r, node.nodeName, node); node = node.nextElementSibling; } return r; } function parseContentProtection(root, contentProtectionParser) { return contentProtectionParser(feedAttributes(root), root); } function parseSegmentBase(root) { var index = reduceChildren(root, function (res, name, node) { if (name == "Initialization") { res.initialization = parseInitialization(node); } return res; }, feedAttributes(root)); if (root.nodeName == "SegmentBase") { index.indexType = "base"; index.timeline = []; } return index; } function parseMultipleSegmentBase(root) { return reduceChildren(root, function (res, name, node) { if (name == "SegmentTimeline") { res.indexType = "timeline"; res.timeline = parseSegmentTimeline(node); } return res; }, parseSegmentBase(root)); } function parseSegmentTimeline(root) { return reduceChildren(root, function (arr, name, node) { var len = arr.length; var seg = feedAttributes(node); if (seg.ts == null) { var prev = len > 0 && arr[len - 1]; seg.ts = prev ? prev.ts + prev.d * (prev.r + 1) : 0; } if (seg.r == null) { seg.r = 0; } arr.push(seg); return arr; }, []); } function parseInitializationAttribute(attrValue) { return { media: attrValue, range: undefined }; } function parseInitialization(root) { var range, media; if (root.hasAttribute("range")) range = parseByteRange(root.getAttribute("range")); if (root.hasAttribute("sourceURL")) media = root.getAttribute("sourceURL"); return { range: range, media: media }; } function parseSegmentTemplate(root) { var base = parseMultipleSegmentBase(root); if (!base.indexType) { base.indexType = "template"; } return base; } function parseSegmentList(root) { var base = parseMultipleSegmentBase(root); base.list = []; base.indexType = "list"; return reduceChildren(root, function (res, name, node) { if (name == "SegmentURL") { res.list.push(feedAttributes(node)); } return res; }, base); } function parseRepresentation(root) { var rep = reduceChildren(root, function (res, name, node) { switch (name) { // case "FramePacking": break; // case "AudioChannelConfiguration": break; // case "ContentProtection": res.contentProtection = parseContentProtection(node); break; // case "EssentialProperty": break; // case "SupplementalProperty": break; // case "InbandEventStream": break; case "BaseURL": res.baseURL = node.textContent;break; // case "SubRepresentation": break; case "SegmentBase": res.index = parseSegmentBase(node);break; case "SegmentList": res.index = parseSegmentList(node);break; case "SegmentTemplate": res.index = parseSegmentTemplate(node);break; } return res; }, {}); return feedAttributes(root, rep); } function parseContentComponent(root) { return feedAttributes(root); } function parseAdaptationSet(root, contentProtectionParser) { var res = reduceChildren(root, function (res, name, node) { switch (name) { // case "Accessibility": break; // case "Role": break; // case "Rating": break; // case "Viewpoint": break; case "ContentProtection": res.contentProtection = parseContentProtection(node, contentProtectionParser);break; case "ContentComponent": res.contentComponent = parseContentComponent(node);break; case "BaseURL": res.baseURL = node.textContent;break; case "SegmentBase": res.index = parseSegmentBase(node);break; case "SegmentList": res.index = parseSegmentList(node);break; case "SegmentTemplate": res.index = parseSegmentTemplate(node);break; case "Representation": var rep = parseRepresentation(node); if (rep.id == null) { rep.id = res.representations.length; } res.representations.push(rep);break; } return res; }, { representations: [] }); return feedAttributes(root, res); } function parsePeriod(root, contentProtectionParser) { var attrs = feedAttributes(root, reduceChildren(root, function (res, name, node) { switch (name) { case "BaseURL": res.baseURL = node.textContent;break; case "AdaptationSet": var ada = parseAdaptationSet(node, contentProtectionParser); if (ada.id == null) { ada.id = res.adaptations.length; } res.adaptations.push(ada);break; } return res; }, { adaptations: [] })); if (attrs.baseURL) { _.each(attrs.adaptations, function (adaptation) { return _.defaults(adaptation, { baseURL: attrs.baseURL }); }); } return attrs; } function parseFromDocument(document, contentProtectionParser) { var root = document.documentElement; assert.equal(root.nodeName, "MPD", "parser: document root should be MPD"); var manifest = reduceChildren(root, function (res, name, node) { switch (name) { case "BaseURL": res.baseURL = node.textContent;break; case "Location": res.locations.push(node.textContent);break; case "Period": res.periods.push(parsePeriod(node, contentProtectionParser));break; } return res; }, { transportType: "dash", periods: [], locations: [] }); manifest = feedAttributes(root, manifest); if (/isoff-live/.test(manifest.profiles)) { var adaptations = manifest.periods[0].adaptations; var videoAdaptation = _.find(adaptations, function (a) { return a.mimeType == "video/mp4"; }); var videoIndex = videoAdaptation && videoAdaptation.index; if (false) { assert(videoIndex && (videoIndex.indexType == "timeline" || videoIndex.indexType == "template")); assert(manifest.availabilityStartTime); } var lastRef; if (videoIndex.timeline) { lastRef = calcLastRef(videoIndex); } else { lastRef = Date.now() / 1000 - 60; } manifest.availabilityStartTime = manifest.availabilityStartTime.getTime() / 1000; manifest.presentationLiveGap = Date.now() / 1000 - (lastRef + manifest.availabilityStartTime); } return manifest; } function parseFromString(manifest, contentProtectionParser) { return parseFromDocument(new DOMParser().parseFromString(manifest, "application/xml"), contentProtectionParser); } function parser(manifest, contentProtectionParser) { if (_.isString(manifest)) return parseFromString(manifest, contentProtectionParser); if (manifest instanceof window.Document) return parseFromDocument(manifest, contentProtectionParser); throw new Error("parser: unsupported type to parse"); } parser.parseFromString = parseFromString; parser.parseFromDocument = parseFromDocument; module.exports = parser; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; module.exports = { smooth: __webpack_require__(41), dash: __webpack_require__(37) }; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var _require = __webpack_require__(3); var Observable = _require.Observable; var empty = Observable.empty; var just = Observable.just; var request = __webpack_require__(14); var _require2 = __webpack_require__(11); var resolveURL = _require2.resolveURL; var _require3 = __webpack_require__(7); var bytesToStr = _require3.bytesToStr; var log = __webpack_require__(4); var createSmoothStreamingParser = __webpack_require__(43); var _require4 = __webpack_require__(42); var patchSegment = _require4.patchSegment; var createVideoInitSegment = _require4.createVideoInitSegment; var createAudioInitSegment = _require4.createAudioInitSegment; var getMdat = _require4.getMdat; var getTraf = _require4.getTraf; var parseTfrf = _require4.parseTfrf; var parseTfxd = _require4.parseTfxd; var _require5 = __webpack_require__(44); var parseSami = _require5.parseSami; var _require6 = __webpack_require__(45); var parseTTML = _require6.parseTTML; var TT_PARSERS = { "application/x-sami": parseSami, "application/smil": parseSami, "application/ttml+xml": parseTTML, "application/ttml+xml+mp4": parseTTML, "text/vtt": _.identity }; var ISM_REG = /\.(isml?)(\?token=\S+)?$/; var WSX_REG = /\.wsx?(\?token=\S+)?/; var TOKEN_REG = /\?token=(\S+)/; function byteRange(_ref) { var start = _ref[0]; var end = _ref[1]; if (!end || end === Infinity) { return "bytes=" + +start + "-"; } else { return "bytes=" + +start + "-" + +end; } } function extractISML(doc) { return doc.getElementsByTagName("media")[0].getAttribute("src"); } function extractToken(url) { var tokenMatch = url.match(TOKEN_REG); return tokenMatch && tokenMatch[1] || ""; } function replaceToken(url, token) { if (token) { return url.replace(TOKEN_REG, "?token=" + token); } else { return url.replace(TOKEN_REG, ""); } } function resolveManifest(url) { var ismMatch = url.match(ISM_REG); if (ismMatch) { return url.replace(ismMatch[1], ismMatch[1] + "/manifest"); } else { return url; } } function buildSegmentURL(adaptation, representation, segment) { return resolveURL(adaptation.rootURL, adaptation.baseURL, representation.baseURL).replace(/\{bitrate\}/g, representation.bitrate).replace(/\{start time\}/g, segment.time); } var req = function req(reqOptions) { reqOptions.withMetadata = true; return request(reqOptions); }; module.exports = function () { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var smoothManifestParser = createSmoothStreamingParser(options); var manifestPipeline = { resolver: function resolver(_ref2) { var url = _ref2.url; var resolving; var token = extractToken(url); if (WSX_REG.test(url)) { resolving = req({ url: replaceToken(url, ""), format: "document" }).map(function (_ref3) { var blob = _ref3.blob; return extractISML(blob); }); } else { resolving = just(url); } return resolving.map(function (url) { return { url: replaceToken(resolveManifest(url), token) }; }); }, loader: function loader(_ref4) { var url = _ref4.url; return req({ url: url, format: "document" }); }, parser: function parser(_ref5) { var response = _ref5.response; return just({ manifest: smoothManifestParser(response.blob), url: response.url }); } }; function extractTimingsInfos(blob, adaptation, segment) { var nextSegments; var currentSegment; if (adaptation.isLive) { var traf = getTraf(blob); if (traf) { nextSegments = parseTfrf(traf); currentSegment = parseTfxd(traf); } else { log.warn("smooth: could not find traf atom"); } } else { nextSegments = null; } if (!currentSegment) { currentSegment = { d: segment.duration, ts: segment.time }; } return { nextSegments: nextSegments, currentSegment: currentSegment }; } var segmentPipeline = { loader: function loader(_ref6) { var adaptation = _ref6.adaptation; var representation = _ref6.representation; var segment = _ref6.segment; if (segment.init) { var blob; var protection = adaptation.smoothProtection || {}; switch (adaptation.type) { case "video": blob = createVideoInitSegment(representation.index.timescale, representation.width, representation.height, 72, 72, 4, // vRes, hRes, nal representation.codecPrivateData, protection.keyId, // keyId protection.keySystems // pssList );break; case "audio": blob = createAudioInitSegment(representation.index.timescale, representation.channels, representation.bitsPerSample, representation.packetSize, representation.samplingRate, representation.codecPrivateData, protection.keyId, // keyId protection.keySystems // pssList );break; } return just({ blob: blob, size: blob.length, duration: 100 }); } else { var headers; var range = segment.range; if (range) { headers = { "Range": byteRange(range) }; } var url = buildSegmentURL(adaptation, representation, segment); return req({ url: url, format: "arraybuffer", headers: headers }); } }, parser: function parser(_ref7) { var adaptation = _ref7.adaptation; var response = _ref7.response; var segment = _ref7.segment; if (segment.init) { return just({ blob: response.blob, timings: null }); } var blob = new Uint8Array(response.blob); var _extractTimingsInfos = extractTimingsInfos(blob, adaptation, segment); var nextSegments = _extractTimingsInfos.nextSegments; var currentSegment = _extractTimingsInfos.currentSegment; return just({ blob: patchSegment(blob, currentSegment.ts), nextSegments: nextSegments, currentSegment: currentSegment }); } }; var textTrackPipeline = { loader: function loader(_ref8) { var adaptation = _ref8.adaptation; var representation = _ref8.representation; var segment = _ref8.segment; if (segment.init) return empty(); var mimeType = representation.mimeType; var url = buildSegmentURL(adaptation, representation, segment); if (mimeType.indexOf("mp4") >= 0) { // in case of TTML declared inside // playlists, the TTML file is embededded // inside an mp4 fragment. return req({ url: url, format: "arraybuffer" }); } else { return req({ url: url, format: "text" }); } }, parser: function parser(_ref9) { var response = _ref9.response; var adaptation = _ref9.adaptation; var representation = _ref9.representation; var segment = _ref9.segment; var lang = adaptation.lang; var mimeType = representation.mimeType; var parser_ = TT_PARSERS[mimeType]; if (!parser_) { throw new Error("smooth: could not find a text-track parser for the type " + mimeType); } var blob = response.blob; var text; // in case of TTML declared inside playlists, the TTML file is // embededded inside an mp4 fragment. if (mimeType.indexOf("mp4") >= 0) { blob = new Uint8Array(blob); text = bytesToStr(getMdat(blob)); } else { // vod is simple WebVTT or TTML text text = blob; } var _extractTimingsInfos2 = extractTimingsInfos(blob, adaptation, segment); var nextSegments = _extractTimingsInfos2.nextSegments; var currentSegment = _extractTimingsInfos2.currentSegment; return just({ blob: parser_(text, lang, segment.time / representation.index.timescale), currentSegment: currentSegment, nextSegments: nextSegments }); } }; return { manifest: manifestPipeline, audio: segmentPipeline, video: segmentPipeline, text: textTrackPipeline }; }; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var assert = __webpack_require__(2); var _require = __webpack_require__(7); var concat = _require.concat; var strToBytes = _require.strToBytes; var bytesToStr = _require.bytesToStr; var hexToBytes = _require.hexToBytes; var bytesToHex = _require.bytesToHex; var be2toi = _require.be2toi; var itobe2 = _require.itobe2; var be4toi = _require.be4toi; var itobe4 = _require.itobe4; var be8toi = _require.be8toi; var itobe8 = _require.itobe8; var FREQS = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; var boxName = _.memoize(strToBytes); function Atom(name, buff) { if (false) assert(name.length === 4); var len = buff.length + 8; return concat(itobe4(len), boxName(name), buff); } function readUuid(buf, id1, id2, id3, id4) { var i = 0, l = buf.length, len; while (i < l) { len = be4toi(buf, i); if (be4toi(buf, i + 4) === 0x75756964 /* === "uuid" */ && be4toi(buf, i + 8) === id1 && be4toi(buf, i + 12) === id2 && be4toi(buf, i + 16) === id3 && be4toi(buf, i + 20) === id4) return buf.subarray(i + 24, i + len); i += len; } } function findAtom(buf, atomName) { var i = 0, l = buf.length; var name, size; while (i + 8 < l) { size = be4toi(buf, i); name = be4toi(buf, i + 4); assert(size > 0, "dash: out of range size"); if (name === atomName) { break; } else { i += size; } } if (i >= l) return; return buf.subarray(i + 8, i + size); } var atoms = { mult: function mult(name, children) { return Atom(name, concat.apply(null, children)); }, /** * {String} name ("avc1" or "encv") * {Number} drefIdx (shall be 1) * {Number} width * {Number} height * {Number} hRes (horizontal resolution, eg 72) * {Number} vRes (horizontal resolution, eg 72) * {Number} colorDepth (eg 24) * {Uint8Array} avcc (Uint8Array representing the avcC atom) * {Uint8Array} sinf (Uint8Array representing the sinf atom, only if name == "encv") */ avc1encv: function avc1encv(name, drefIdx, width, height, hRes, vRes, encName, colorDepth, avcc, sinf) { if (false) assert(name === "avc1" || name === "encv", "should be avc1 or encv atom"); return Atom(name, concat(6, // 6 bytes reserved itobe2(drefIdx), 16, // drefIdx + QuickTime reserved, zeroes itobe2(width), // size 2 w itobe2(height), // size 2 h itobe2(hRes), 2, // reso 4 h itobe2(vRes), 2 + 4, // reso 4 v + QuickTime reserved, zeroes [0, 1, encName.length], // frame count (default 1) strToBytes(encName), // 1byte len + encoder name str 31 - encName.length, // + padding itobe2(colorDepth), // color depth [0xFF, 0xFF], // reserved ones avcc, // avcc atom, name === "encv" ? sinf : [])); }, /** * {String} spsHex * {String} ppsHex * {Number} nalLen (NAL Unit length: 1, 2 or 4 bytes) * eg: avcc(0x4d, 0x40, 0x0d, 4, 0xe1, "674d400d96560c0efcb80a70505050a0", 1, "68ef3880") */ avcc: function avcc(sps, pps, nalLen) { var nal = nalLen === 2 ? 0x1 : nalLen === 4 ? 0x3 : 0x0; // Deduce AVC Profile from SPS var h264Profile = sps[1]; var h264CompatibleProfile = sps[2]; var h264Level = sps[3]; return Atom("avcC", concat([1, h264Profile, h264CompatibleProfile, h264Level, 0x3F << 2 | nal, 0xE0 | 1], itobe2(sps.length), sps, [1], itobe2(pps.length), pps)); }, dref: function dref(url) { // only one description here... FIXME return Atom("dref", concat(7, [1], url)); }, /** * {Number} stream * {String} codecPrivateData (hex string) * eg: esds(1, 98800, "1190") */ esds: function esds(stream, codecPrivateData) { return Atom("esds", concat(4, [0x03, 0x19], itobe2(stream), [0x00, 0x04, 0x11, 0x40, 0x15], 11, [0x05, 0x02], hexToBytes(codecPrivateData), [0x06, 0x01, 0x02])); }, /** * {String} dataFormat, four letters (eg "avc1") */ frma: function frma(dataFormat) { if (false) assert.equal(dataFormat.length, 4, "wrong data format length"); return Atom("frma", strToBytes(dataFormat)); }, free: function free(length) { return Atom("free", new Uint8Array(length - 8)); }, ftyp: function ftyp(majorBrand, brands) { return Atom("ftyp", concat.apply(null, [strToBytes(majorBrand), [0, 0, 0, 1]].concat(brands.map(strToBytes)))); }, /** * {String} type ("video" or "audio") */ hdlr: function hdlr(type) { type = type === "audio" ? "soun" : // audio "vide"; // video return Atom("hdlr", concat(8, strToBytes(type), 12, strToBytes("Media Handler"))); }, mdhd: function mdhd(timescale) { return Atom("mdhd", concat(12, itobe4(timescale), 8)); }, moof: function moof(mfhd, traf) { return atoms.mult("moof", [mfhd, traf]); }, /** * {String} name ("mp4a" or "enca") * {Number} drefIdx * {Number} channelsCount * {Number} sampleSize * {Number} packetSize * {Number} sampleRate * {Uint8Array} esds (Uint8Array representing the esds atom) * {Uint8Array} sinf (Uint8Array representing the sinf atom, only if name == "enca") */ mp4aenca: function mp4aenca(name, drefIdx, channelsCount, sampleSize, packetSize, sampleRate, esds, sinf) { return Atom(name, concat(6, itobe2(drefIdx), 8, itobe2(channelsCount), itobe2(sampleSize), 2, itobe2(packetSize), itobe2(sampleRate), 2, esds, name === "enca" ? sinf : [])); }, mvhd: function mvhd(timescale, trackId) { return Atom("mvhd", concat(12, itobe4(timescale), 4, [0, 1], 2, // we assume rate = 1; [1, 0], 10, // we assume volume = 100%; [0, 1], 14, // default matrix [0, 1], 14, // default matrix [64, 0, 0, 0], 26, itobe2(trackId + 1) // next trackId (=trackId + 1); )); }, /** * {String} systemId Hex string representing the CDM, 16 bytes. eg 1077efec-c0b2-4d02-ace3-3c1e52e2fb4b for ClearKey * {Uint8Array} privateData Data associated to protection specific system * {[]Uint8Array} keyIds List of key ids contained in the PSSH */ pssh: function pssh(systemId) { var privateData = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; var keyIds = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; systemId = systemId.replace(/-/g, ""); assert(systemId.length === 32, "wrong system id length"); var version; var kidList; var kidCount = keyIds.length; if (kidCount > 0) { version = 1; kidList = concat.apply(null, [itobe4(kidCount)].concat(keyIds)); } else { version = 0; kidList = []; } return Atom("pssh", concat([version, 0, 0, 0], hexToBytes(systemId), kidList, itobe4(privateData.length), privateData)); }, saio: function saio(mfhd, tfhd, tfdt, trun) { return Atom("saio", concat(4, [0, 0, 0, 1], // ?? itobe4(mfhd.length + tfhd.length + tfdt.length + trun.length + 8 + 8 + 8 + 8))); }, /** * {Uint8Array} sencData (including 8 bytes flags and entries count) */ saiz: function saiz(senc) { if (senc.length === 0) { return Atom("saiz", new Uint8Array()); } var flags = be4toi(senc, 0); var entries = be4toi(senc, 4); var arr = new Uint8Array(9 + entries); arr.set(itobe4(entries), 5); var i = 9; var j = 8; var pairsCnt; var pairsLen; while (j < senc.length) { j += 8; // assuming IV is 8 bytes TODO handle 16 bytes IV // if we have extradata for each entry if ((flags & 0x2) === 0x2) { pairsLen = 2; pairsCnt = be2toi(senc, j); j += 2 + pairsCnt * 6; } else { pairsCnt = 0; pairsLen = 0; } arr[i] = pairsCnt * 6 + 8 + pairsLen; i++; } return Atom("saiz", arr); }, /** * {String} schemeType, four letters (eg "cenc" for Common Encryption) * {Number} schemeVersion (eg 65536) */ schm: function schm(schemeType, schemeVersion) { if (false) assert.equal(schemeType.length, 4, "wrong scheme type length"); return Atom("schm", concat(4, strToBytes(schemeType), itobe4(schemeVersion))); }, senc: function senc(buf) { return Atom("senc", buf); }, smhd: function smhd() { return Atom("smhd", new Uint8Array(8)); }, /** * {Array} representations (arrays of Uint8Array, typically [avc1] or [encv, avc1]) */ stsd: function stsd(reps) { // only one description here... FIXME return Atom("stsd", concat.apply(null, [7, [reps.length]].concat(reps))); }, tkhd: function tkhd(width, height, trackId) { return Atom("tkhd", concat(itobe4(1 + 2 + 4), 8, // we assume track is enabled, in media and in preview. itobe4(trackId), 20, // we assume trackId = 1; [1, 0, 0, 0], // we assume volume = 100%; [0, 1, 0, 0], 12, // default matrix [0, 1, 0, 0], 12, // default matrix [64, 0, 0, 0], // ?? itobe2(width), 2, // width (TODO handle fixed) itobe2(height), 2 // height (TODO handle fixed) )); }, trex: function trex(trackId) { // default sample desc idx = 1 return Atom("trex", concat(4, itobe4(trackId), [0, 0, 0, 1], 12)); }, tfdt: function tfdt(decodeTime) { return Atom("tfdt", concat([1, 0, 0, 0], itobe8(decodeTime))); }, /** * {Number} algId (eg 1) * {Number} ivSize (eg 8) * {String} keyId Hex KID 93789920e8d6520098577df8f2dd5546 */ tenc: function tenc(algId, ivSize, keyId) { if (false) assert.equal(keyId.length, 32, "wrong default KID length"); return Atom("tenc", concat(6, [algId, ivSize], hexToBytes(keyId))); }, traf: function traf(tfhd, tfdt, trun, senc, mfhd) { var trafs = [tfhd, tfdt, trun]; if (senc) { trafs.push(atoms.senc(senc), atoms.saiz(senc), atoms.saio(mfhd, tfhd, tfdt, trun)); } return atoms.mult("traf", trafs); }, trun: function trun(oldtrun) { var headersLast = oldtrun[11]; var hasDataOffset = headersLast & 0x01; if (hasDataOffset) { return oldtrun; } // If no dataoffset is present, we change the headers and add one var trun = new Uint8Array(oldtrun.length + 4); trun.set(itobe4(oldtrun.length + 4), 0); trun.set(oldtrun.slice(4, 16), 4); // name + (version + headers) + samplecount trun[11] = trun[11] | 0x01; // add data offset header info trun.set([0, 0, 0, 0], 16); // data offset trun.set(oldtrun.slice(16, oldtrun.length), 20); return trun; }, vmhd: function vmhd() { var arr = new Uint8Array(12); arr[3] = 1; // QuickTime... return Atom("vmhd", arr); } }; var reads = { traf: function traf(buff) { var moof = findAtom(buff, 0x6D6F6F66); if (moof) return findAtom(moof, 0x74726166);else return null; }, /** * Extract senc data (derived from UUID MS Atom) * {Uint8Array} traf */ senc: function senc(traf) { return readUuid(traf, 0xA2394F52, 0x5A9B4F14, 0xA2446C42, 0x7C648DF4); }, /** * Extract tfxd data (derived from UUID MS Atom) * {Uint8Array} traf */ tfxd: function tfxd(traf) { return readUuid(traf, 0x6D1D9B05, 0x42D544E6, 0x80E2141D, 0xAFF757B2); }, /** * Extract tfrf data (derived from UUID MS Atom) * {Uint8Array} traf */ tfrf: function tfrf(traf) { return readUuid(traf, 0xD4807EF2, 0XCA394695, 0X8E5426CB, 0X9E46A79F); }, mdat: function mdat(buff) { return findAtom(buff, 0x6D646174 /* "mdat" */); } }; /** * Return AAC ES Header (hexstr form) * * {Number} type * 1 = AAC Main * 2 = AAC LC * cf http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio * {Number} frequency * {Number} chans (1 or 2) */ function aacesHeader(type, frequency, chans) { var freq = FREQS.indexOf(frequency); if (false) assert(freq >= 0, "non supported frequency"); // TODO : handle Idx = 15... var val; val = (type & 0x3F) << 0x4; val = (val | freq & 0x1F) << 0x4; val = (val | chans & 0x1F) << 0x3; return bytesToHex(itobe2(val)); } function moovChildren(mvhd, mvex, trak, pssList) { var moov = [mvhd, mvex, trak]; _.each(pssList, function (pss) { var pssh = atoms.pssh(pss.systemId, pss.privateData, pss.keyIds); moov.push(pssh); }); return moov; } function patchTrunDataOffset(segment, trunoffset, dataOffset) { // patch trun dataoffset with new moof atom size segment.set(itobe4(dataOffset), trunoffset + 16); } function createNewSegment(segment, newmoof, oldmoof, trunoffset) { var segmentlen = segment.length; var newmooflen = newmoof.length; var oldmooflen = oldmoof.length; var mdat = segment.subarray(oldmooflen, segmentlen); var newSegment = new Uint8Array(newmooflen + (segmentlen - oldmooflen)); newSegment.set(newmoof, 0); newSegment.set(mdat, newmooflen); patchTrunDataOffset(newSegment, trunoffset, newmoof.length + 8); return newSegment; } /* function patchSegmentInPlace(segment, newmoof, oldmoof, trunoffset) { var free = oldmoof.length - newmoof.length; segment.set(newmoof, 0); segment.set(atoms.free(free), newmoof.length); patchTrunDataOffset(segment, trunoffset, newmoof.length + 8 + free); return segment; } */ function createInitSegment(timescale, type, stsd, mhd, width, height, pssList) { var stbl = atoms.mult("stbl", [stsd, Atom("stts", new Uint8Array(0x08)), Atom("stsc", new Uint8Array(0x08)), Atom("stsz", new Uint8Array(0x0c)), Atom("stco", new Uint8Array(0x08))]); var url = Atom("url ", new Uint8Array([0, 0, 0, 1])); var dref = atoms.dref(url); var dinf = atoms.mult("dinf", [dref]); var minf = atoms.mult("minf", [mhd, dinf, stbl]); var hdlr = atoms.hdlr(type); var mdhd = atoms.mdhd(timescale); //this one is really important var mdia = atoms.mult("mdia", [mdhd, hdlr, minf]); var tkhd = atoms.tkhd(width, height, 1); var trak = atoms.mult("trak", [tkhd, mdia]); var trex = atoms.trex(1); var mvex = atoms.mult("mvex", [trex]); var mvhd = atoms.mvhd(timescale, 1); // in fact, we don"t give a shit about this value ;) var moov = atoms.mult("moov", moovChildren(mvhd, mvex, trak, pssList)); var ftyp = atoms.ftyp("isom", ["isom", "iso2", "iso6", "avc1", "dash"]); return concat(ftyp, moov); } module.exports = { getMdat: reads.mdat, getTraf: reads.traf, parseTfrf: function parseTfrf(traf) { var tfrf = reads.tfrf(traf); if (!tfrf) return []; var frags = []; var version = tfrf[0]; var fragCount = tfrf[4]; for (var i = 0; i < fragCount; i++) { var d, ts; if (version == 1) { ts = be8toi(tfrf, 16 * i + 5); d = be8toi(tfrf, 16 * i + 5 + 8); } else { ts = be4toi(tfrf, 8 * i + 5); d = be4toi(tfrf, 8 * i + 5 + 4); } frags.push({ ts: ts, d: d }); } return frags; }, parseTfxd: function parseTfxd(traf) { var tfxd = reads.tfxd(traf); if (tfxd) { return { d: be8toi(tfxd, 12), ts: be8toi(tfxd, 4) }; } }, /** * Return full Init segment as Uint8Array * * Number timescale (lowest number, this one will be set into mdhd, *10000 in mvhd) Eg 1000 * Number width * Number height * Number hRes * Number vRes * Number nalLength (1, 2 or 4) * String SPShexstr * String PPShexstr * Array (optional) pssList. List of dict {systemId: "DEADBEEF", codecPrivateData: "DEAFBEEF"} listing all Protection Systems * String keyId (hex string representing the key Id, 32 chars. eg. a800dbed49c12c4cb8e0b25643844b9b) * * */ createVideoInitSegment: function createVideoInitSegment(timescale, width, height, hRes, vRes, nalLength, codecPrivateData, keyId, pssList) { if (!pssList) pssList = []; var _codecPrivateData$split = codecPrivateData.split("00000001"); var spsHex = _codecPrivateData$split[1]; var ppsHex = _codecPrivateData$split[2]; var sps = hexToBytes(spsHex); var pps = hexToBytes(ppsHex); // TODO NAL length is forced to 4 var avcc = atoms.avcc(sps, pps, nalLength); var stsd; if (!pssList.length) { var avc1 = atoms.avc1encv("avc1", 1, width, height, hRes, vRes, "AVC Coding", 24, avcc); stsd = atoms.stsd([avc1]); } else { var tenc = atoms.tenc(1, 8, keyId); var schi = atoms.mult("schi", [tenc]); var schm = atoms.schm("cenc", 65536); var frma = atoms.frma("avc1"); var sinf = atoms.mult("sinf", [frma, schm, schi]); var encv = atoms.avc1encv("encv", 1, width, height, hRes, vRes, "AVC Coding", 24, avcc, sinf); stsd = atoms.stsd([encv]); } return createInitSegment(timescale, "video", stsd, atoms.vmhd(), width, height, pssList); }, /** * Return full Init segment as Uint8Array * * Number channelsCount * Number sampleSize * Number packetSize * Number sampleRate * String codecPrivateData * Array (optional) pssList. List of dict {systemId: "DEADBEEF", codecPrivateData: "DEAFBEEF"} listing all Protection Systems * String keyId (hex string representing the key Id, 32 chars. eg. a800dbed49c12c4cb8e0b25643844b9b) * * */ createAudioInitSegment: function createAudioInitSegment(timescale, channelsCount, sampleSize, packetSize, sampleRate, codecPrivateData, keyId, pssList) { if (!pssList) pssList = []; if (!codecPrivateData) codecPrivateData = aacesHeader(2, sampleRate, channelsCount); var esds = atoms.esds(1, codecPrivateData); var stsd; if (!pssList.length) { var mp4a = atoms.mp4aenca("mp4a", 1, channelsCount, sampleSize, packetSize, sampleRate, esds); stsd = atoms.stsd([mp4a]); } else { var tenc = atoms.tenc(1, 8, keyId); var schi = atoms.mult("schi", [tenc]); var schm = atoms.schm("cenc", 65536); var frma = atoms.frma("mp4a"); var sinf = atoms.mult("sinf", [frma, schm, schi]); var enca = atoms.mp4aenca("enca", 1, channelsCount, sampleSize, packetSize, sampleRate, esds, sinf); stsd = atoms.stsd([enca]); } return createInitSegment(timescale, "audio", stsd, atoms.smhd(), 0, 0, pssList); }, patchSegment: function patchSegment(segment, decodeTime) { if (false) { // TODO handle segments with styp/free... var name = bytesToStr(segment.subarray(4, 8)); assert(name === "moof"); } var oldmoof = segment.subarray(0, be4toi(segment, 0)); var newtfdt = atoms.tfdt(decodeTime); // reads [moof[mfhd|traf[tfhd|trun|..]]] var tfdtlen = newtfdt.length; var mfhdlen = be4toi(oldmoof, 8); var traflen = be4toi(oldmoof, 8 + mfhdlen); var tfhdlen = be4toi(oldmoof, 8 + mfhdlen + 8); var trunlen = be4toi(oldmoof, 8 + mfhdlen + 8 + tfhdlen); var oldmfhd = oldmoof.subarray(8, 8 + mfhdlen); var oldtraf = oldmoof.subarray(8 + mfhdlen + 8, 8 + mfhdlen + 8 + traflen - 8); var oldtfhd = oldtraf.subarray(0, tfhdlen); var oldtrun = oldtraf.subarray(tfhdlen, tfhdlen + trunlen); // force trackId=1 since trackIds are not always reliable... oldtfhd.set([0, 0, 0, 1], 12); var oldsenc = reads.senc(oldtraf); // writes [moof[mfhd|traf[tfhd|tfdt|trun|senc|saiz|saio]]] var newtrun = atoms.trun(oldtrun); var newtraf = atoms.traf(oldtfhd, newtfdt, newtrun, oldsenc, oldmfhd); var newmoof = atoms.moof(oldmfhd, newtraf); var trunoffset = 8 + mfhdlen + 8 + tfhdlen + tfdtlen; // TODO(pierre): fix patchSegmentInPlace to work with IE11. Maybe // try to put free atom inside traf children return createNewSegment(segment, newmoof, oldmoof, trunoffset); // if (oldmoof.length - newmoof.length >= 8 /* minimum "free" atom size */) { // return patchSegmentInPlace(segment, newmoof, oldmoof, trunoffset); // } // else { // return createNewSegment(segment, newmoof, oldmoof, trunoffset); // } } }; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var assert = __webpack_require__(2); var bytes = __webpack_require__(7); var DEFAULT_MIME_TYPES = { audio: "audio/mp4", video: "video/mp4", text: "application/ttml+xml" }; var DEFAULT_CODECS = { audio: "mp4a.40.2", video: "avc1.4D401E" }; var MIME_TYPES = { "AACL": "audio/mp4", "AVC1": "video/mp4", "H264": "video/mp4", "TTML": "application/ttml+xml+mp4" }; var CODECS = { "AACL": "mp4a.40.5", "AACH": "mp4a.40.5", "AVC1": "avc1.4D401E", "H264": "avc1.4D401E" }; var profiles = { audio: [["Bitrate", "bitrate", parseInt], ["AudioTag", "audiotag", parseInt], ["FourCC", "mimeType", MIME_TYPES], ["FourCC", "codecs", CODECS], ["Channels", "channels", parseInt], ["SamplingRate", "samplingRate", parseInt], ["BitsPerSample", "bitsPerSample", parseInt], ["PacketSize", "packetSize", parseInt], ["CodecPrivateData", "codecPrivateData", String]], video: [["Bitrate", "bitrate", parseInt], ["FourCC", "mimeType", MIME_TYPES], ["FourCC", "codecs", CODECS], ["MaxWidth", "width", parseInt], ["MaxHeight", "height", parseInt], ["CodecPrivateData", "codecPrivateData", String]], text: [["Bitrate", "bitrate", parseInt], ["FourCC", "mimeType", MIME_TYPES]] }; function parseBoolean(val) { if (typeof val == "boolean") { return val; } else if (typeof val == "string") { return val.toUpperCase() === "TRUE"; } else { return false; } } function calcLastRef(index) { var _$last = _.last(index.timeline); var ts = _$last.ts; var r = _$last.r; var d = _$last.d; return (ts + (r + 1) * d) / index.timescale; } function getKeySystems(keyIdBytes) { return [{ // Widevine systemId: "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed", privateData: bytes.concat([0x08, 0x01, 0x12, 0x10], keyIdBytes) }]; } // keyIds: [keyIdBytes], // { // // Clearkey // // (https://dvcs.w3.org/hg/html-media/raw-file/tip/encrypted-media/cenc-format.html) // systemId: "1077efec-c0b2-4d02-ace3-3c1e52e2fb4b", // privateData: bytes.strToBytes(JSON.stringify({ // kids: [bytes.toBase64URL(bytes.bytesToStr(keyIdBytes))], // type: "temporary" // })) // } function createSmoothStreamingParser() { var parserOptions = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var SUGGESTED_PERSENTATION_DELAY = parserOptions.suggestedPresentationDelay || 20; var REFERENCE_DATE_TIME = parserOptions.referenceDateTime || Date.UTC(1970, 0, 1, 0, 0, 0, 0) / 1000; var MIN_REPRESENTATION_BITRATE = parserOptions.minRepresentationBitrate || 190000; var keySystems = parserOptions.keySystems || getKeySystems; function getHexKeyId(buf) { var len = bytes.le2toi(buf, 8); var xml = bytes.bytesToUTF16Str(buf.subarray(10, 10 + len)); var doc = new DOMParser().parseFromString(xml, "application/xml"); var kid = doc.querySelector("KID").textContent; return bytes.guidToUuid(atob(kid)).toLowerCase(); } function reduceChildren(root, fn, init) { var node = root.firstElementChild, r = init; while (node) { r = fn(r, node.nodeName, node); node = node.nextElementSibling; } return r; } function parseProtection(root) { var header = root.firstElementChild; assert.equal(header.nodeName, "ProtectionHeader", "parser: Protection should have ProtectionHeader child"); var privateData = bytes.strToBytes(atob(header.textContent)); var keyId = getHexKeyId(privateData); var keyIdBytes = bytes.hexToBytes(keyId); // remove possible braces var systemId = header.getAttribute("SystemID").toLowerCase().replace(/\{|\}/g, ""); return { keyId: keyId, keySystems: [{ systemId: systemId, privateData: privateData }]. // keyIds: [keyIdBytes], concat(keySystems(keyIdBytes)) }; } function parseC(node, timeline) { var l = timeline.length; var prev = l > 0 ? timeline[l - 1] : { d: 0, ts: 0, r: 0 }; var d = +node.getAttribute("d"); var t = node.getAttribute("t"); var r = +node.getAttribute("r"); // in smooth streaming format, // r refers to number of same duration // chunks, not repetitions (defers from DASH) if (r) r--; if (l > 0 && !prev.d) { prev.d = t - prev.ts; timeline[l - 1] = prev; } if (l > 0 && d == prev.d && t == null) { prev.r += (r || 0) + 1; } else { var ts = t == null ? prev.ts + prev.d * (prev.r + 1) : +t; timeline.push({ d: d, ts: ts, r: r }); } return timeline; } function parseQualityLevel(q, prof) { return _.reduce(prof, function (obj, _ref) { var key = _ref[0]; var name = _ref[1]; var parse = _ref[2]; obj[name] = _.isFunction(parse) ? parse(q.getAttribute(key)) : parse[q.getAttribute(key)]; return obj; }, {}); } // Parse the adaptations (<StreamIndex>) tree containing // representations (<QualityLevels>) and timestamp indexes (<c>). // Indexes can be quite huge, and this function needs to // to be optimized. function parseAdaptation(root, timescale) { if (root.hasAttribute("Timescale")) { timescale = +root.getAttribute("Timescale"); } var type = root.getAttribute("Type"); var subType = root.getAttribute("Subtype"); var profile = profiles[type]; assert(profile, "parser: unrecognized QualityLevel type " + type); var representationCount = 0; var _reduceChildren = reduceChildren(root, function (res, name, node) { switch (name) { case "QualityLevel": var rep = parseQualityLevel(node, profile); // filter out video representations with small bitrates if (type != "video" || rep.bitrate > MIN_REPRESENTATION_BITRATE) { rep.id = representationCount++; res.representations.push(rep); } break; case "c": res.index.timeline = parseC(node, res.index.timeline); break; } return res; }, { representations: [], index: { timeline: [], indexType: "timeline", timescale: timescale, initialization: {} } }); var representations = _reduceChildren.representations; var index = _reduceChildren.index; // we assume that all representations have the same // codec and mimeType assert(representations.length, "parser: adaptation should have at least one representation"); // apply default codec if non-supported var codecs = representations[0].codecs; if (!codecs) { codecs = DEFAULT_CODECS[type]; _.each(representations, function (rep) { return rep.codecs = codecs; }); } // apply default mimetype if non-supported var mimeType = representations[0].mimeType; if (!mimeType) { mimeType = DEFAULT_MIME_TYPES[type]; _.each(representations, function (rep) { return rep.mimeType = mimeType; }); } // TODO(pierre): real ad-insert support if (subType == "ADVT") return null; return { type: type, index: index, representations: representations, name: root.getAttribute("Name"), lang: root.getAttribute("Language"), baseURL: root.getAttribute("Url") }; } function parseFromString(manifest) { return parseFromDocument(new DOMParser().parseFromString(manifest, "application/xml")); } function parseFromDocument(doc) { var root = doc.documentElement; assert.equal(root.nodeName, "SmoothStreamingMedia", "parser: document root should be SmoothStreamingMedia"); assert(/^[2]-[0-2]$/.test(root.getAttribute("MajorVersion") + "-" + root.getAttribute("MinorVersion")), "Version should be 2.0, 2.1 or 2.2"); var timescale = +root.getAttribute("Timescale") || 10000000; var adaptationCount = 0; var _reduceChildren2 = reduceChildren(root, function (res, name, node) { switch (name) { case "Protection": res.protection = parseProtection(node);break; case "StreamIndex": var ada = parseAdaptation(node, timescale); if (ada) { ada.id = adaptationCount++; res.adaptations.push(ada); } break; } return res; }, { protection: null, adaptations: [] }); var protection = _reduceChildren2.protection; var adaptations = _reduceChildren2.adaptations; _.each(adaptations, function (a) { return a.smoothProtection = protection; }); var suggestedPresentationDelay, presentationLiveGap, timeShiftBufferDepth, availabilityStartTime; var isLive = parseBoolean(root.getAttribute("IsLive")); if (isLive) { suggestedPresentationDelay = SUGGESTED_PERSENTATION_DELAY; timeShiftBufferDepth = +root.getAttribute("DVRWindowLength") / timescale; availabilityStartTime = REFERENCE_DATE_TIME; var video = _.find(adaptations, function (a) { return a.type == "video"; }); var audio = _.find(adaptations, function (a) { return a.type == "audio"; }); var lastRef = Math.min(calcLastRef(video.index), calcLastRef(audio.index)); presentationLiveGap = Date.now() / 1000 - (lastRef + availabilityStartTime); } return { transportType: "smoothstreaming", profiles: "", type: isLive ? "dynamic" : "static", suggestedPresentationDelay: suggestedPresentationDelay, timeShiftBufferDepth: timeShiftBufferDepth, presentationLiveGap: presentationLiveGap, availabilityStartTime: availabilityStartTime, periods: [{ duration: (+root.getAttribute("Duration") || Infinity) / timescale, adaptations: adaptations, laFragCount: +root.getAttribute("LookAheadFragmentCount") }] }; } function parser(val) { if (_.isString(val)) return parseFromString(val); if (val instanceof window.Document) return parseFromDocument(val); throw new Error("parser: unsupported type to parse"); } parser.parseFromString = parseFromString; parser.parseFromDocument = parseFromDocument; return parser; } module.exports = createSmoothStreamingParser; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var assert = __webpack_require__(2); var HTML_ENTITIES = /&#([0-9]+);/g; var BR = /<br>/gi; var STYLE = /<style[^>]*>([\s\S]*?)<\/style[^>]*>/i; var PARAG = /\s*<p class=([^>]+)>(.*)/i; var START = /<sync[^>]+?start="?([0-9]*)"?[^0-9]/i; // Really basic CSS parsers using regular-expressions. function rulesCss(str) { var ruleRe = /\.(\S+)\s*{([^}]*)}/gi; var m, langs = {}; while (m = ruleRe.exec(str)) { var name = m[1]; var lang = propCss(m[2], "lang"); if (name && lang) { langs[lang] = name; } } return langs; } function propCss(str, name) { return str.match(new RegExp("\\s*" + name + ":\\s*(\\S+);", "i"))[1]; } function decodeEntities(text) { return text.replace(BR, "\n").replace(HTML_ENTITIES, function ($0, $1) { return String.fromCharCode($1); }); } // Because sami is not really html... we have to use // some kind of regular expressions to parse it... // the cthulhu way :) // The specification being quite clunky, this parser // may not work for every sami input. function parseSami(smi, lang) { var syncOp = /<sync[ >]/ig; var syncCl = /<sync[ >]|<\/body>/ig; var subs = []; var _smi$match = smi.match(STYLE); var css = _smi$match[1]; var up, to = syncCl.exec(smi); var langs = rulesCss(css); var klass = langs[lang]; assert(klass, "sami: could not find lang " + lang + " in CSS"); for (;;) { up = syncOp.exec(smi); to = syncCl.exec(smi); if (!up && !to) break; if (!up || !to || up.index >= to.index) throw new Error("parse error"); var str = smi.slice(up.index, to.index); var tim = str.match(START); if (!tim) throw new Error("parse error: sync time attribute"); var start = +tim[1]; if (isNaN(start)) throw new Error("parse error: sync time attribute NaN"); appendSub(subs, str.split("\n"), start / 1000); } return subs; function appendSub(subs, lines, start) { var i = lines.length, m; while (--i >= 0) { m = lines[i].match(PARAG);if (!m) continue; var _m = m; var kl = _m[1]; var txt = _m[2]; if (klass !== kl) continue; if (txt === "&nbsp;") { _.last(subs).end = start; } else { subs.push({ text: decodeEntities(txt), start: start }); } } } } module.exports = { parseSami: parseSami }; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _ = __webpack_require__(1); var rBr = /<br[^>]+>/gm; var rAbsTime = /^(([0-9]+):)?([0-9]+):([0-9]+)(\.([0-9]+))?$/; var rRelTime = /(([0-9]+)(\.[0-9]+)?)(ms|h|m|s)/; var escape = window.escape; var MULTS = { h: 3600, m: 60, s: 1, ms: 0.001 }; function parseTTML(ttml, lang, offset) { var doc; if (_.isString(ttml)) { doc = new DOMParser().parseFromString(ttml, "text/xml"); } else { doc = ttml; } if (!(doc instanceof window.Document || doc instanceof window.HTMLElement)) throw new Error("ttml: needs a Document to parse"); var node = doc.querySelector("tt"); if (!node) throw new Error("ttml: could not find <tt> tag"); var subs = parseChildren(node.querySelector("body"), 0); _.each(subs, function (s) { s.start += offset; s.end += offset; }); return subs; } // Parse the children of the given node recursively function parseChildren(node, parentOffset) { var siblingOffset = 0; node = node.firstChild; var arr = [], sub; while (node) { if (node.nodeType === 1) { switch (node.tagName.toUpperCase()) { case "P": // p is a textual node, process contents as subtitle sub = parseNode(node, parentOffset, siblingOffset); siblingOffset = sub.end; arr.push(sub); break; case "DIV": // div is container for subtitles, recurse var newOffset = parseTimestamp(node.getAttribute("begin"), 0); if (newOffset == null) newOffset = parentOffset; arr.push.apply(arr, parseChildren(node, newOffset)); break; } } node = node.nextSibling; } return arr; } // Parse a node for text content function parseNode(node, parentOffset, siblingOffset) { var start = parseTimestamp(node.getAttribute("begin"), parentOffset); var end = parseTimestamp(node.getAttribute("end"), parentOffset); var dur = parseTimestamp(node.getAttribute("dur"), 0); if (!_.isNumber(start) && !_.isNumber(end) && !_.isNumber(dur)) throw new Error("ttml: unsupported timestamp format"); if (dur > 0) { if (start == null) start = siblingOffset || parentOffset; if (end == null) end = start + dur; } else if (end == null) { // No end given, infer duration if possible // Otherwise, give end as MAX_VALUE end = parseTimestamp(node.getAttribute("duration"), 0); if (end >= 0) { end += start; } else { end = Number.MAX_VALUE; } } return { // Trim left and right whitespace from text and convert non-explicit line breaks id: node.getAttribute("xml:id") || node.getAttribute("id"), text: decodeURIComponent(escape(node.innerHTML.replace(rBr, "\n"))), start: start, end: end }; } // Time may be: // * absolute to timeline (hh:mm:ss.ms) // * relative (decimal followed by metric) ex: 3.4s, 5.7m function parseTimestamp(time, offset) { if (!time) return; var match; // Parse absolute times ISO 8601 format ([hh:]mm:ss[.mmm]) match = time.match(rAbsTime); if (match) { var _match = match; var h = _match[2]; var m = _match[3]; var s = _match[4]; var ms = _match[6]; return parseInt(h || 0, 10) * 3600 + parseInt(m, 10) * 60 + parseInt(s, 10) + parseFloat("0." + ms); } // Parse relative times (fraction followed by a unit metric d.ddu) match = time.match(rRelTime); if (match) { var _match2 = match; var n = _match2[1]; var metric = _match2[4]; return parseFloat(n) * MULTS[metric] + offset; } } module.exports = { parseTTML: parseTTML }; /***/ }, /* 46 */ /***/ function(module, exports) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; function ArraySet() { this.arr = []; } ArraySet.prototype.add = function (x) { this.arr.push(x); }; ArraySet.prototype.remove = function (x) { var i = this.arr.indexOf(x); if (i >= 0) this.arr.splice(i, 1); }; ArraySet.prototype.test = function (x) { return this.arr.indexOf(x) >= 0; }; ArraySet.prototype.size = function () { return this.arr.length; }; module.exports = { ArraySet: ArraySet }; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015 CANAL+ Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var _require = __webpack_require__(9); var bufferedToArray = _require.bufferedToArray; var interval; var closeBtn; var reUnescapedHtml = /[&<>"']/g; var htmlEscapes = { "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;" }; function escape(string) { return string == null ? "" : String(string).replace(reUnescapedHtml, function (match) { return htmlEscapes[match]; }); } function bpsToKbps(b) { return (b / 1000).toFixed(3); } function getDebug(player) { var avr = player.getAverageBitrates(); var avrAudio, avrVideo; avr.video.subscribe(function (a) { return avrVideo = a | 0; }).dispose(); avr.audio.subscribe(function (a) { return avrAudio = a | 0; }).dispose(); return { manifest: player.man, version: player.version, timeFragment: player.frag, currentTime: player.getCurrentTime(), state: player.getPlayerState(), buffer: bufferedToArray(player.video.buffered), volume: player.getVolume(), video: { adaptation: player.adas.video, representation: player.reps.video, maxBitrate: player.getVideoMaxBitrate(), bufferSize: player.getVideoBufferSize(), avrBitrate: avrVideo }, audio: { adaptation: player.adas.audio, representation: player.reps.audio, maxBitrate: player.getAudioMaxBitrate(), bufferSize: player.getAudioBufferSize(), avrBitrate: avrAudio } }; } function update(player, videoElement) { var infoElement = videoElement.parentNode.querySelector("#cp--debug-infos-content"); if (infoElement) { var infos; try { infos = getDebug(player); } catch (e) { return; } var _infos = infos; var video = _infos.video; var audio = _infos.audio; var manifest = _infos.manifest; var secureHTML = "<b>Player v" + infos.version + "</b> (" + infos.state + ")<br>"; if (manifest && video && audio) { secureHTML += ["Container: " + escape(manifest.transportType), "Live: " + escape("" + manifest.isLive), // `Playing bitrate: ${video.representation.bitrate}/${audio.representation.bitrate}`, "Downloading bitrate (Kbit/s): " + bpsToKbps(video.representation.bitrate) + "/" + bpsToKbps(audio.representation.bitrate), "Estimated bandwidth (Kbit/s): " + bpsToKbps(video.avrBitrate) + "/" + bpsToKbps(audio.avrBitrate), "Location: " + manifest.locations[0]].join("<br>"); } // Representation: ${escape(video.adaptation.id + "/" + video.representation.id)}<br>${getCodec(video.representation)}<br> // Buffered: ${escape(JSON.stringify(infos.buffer))}<br> // <br><b>Audio</b><br> // Representation: ${escape(audio.adaptation.id + "/" + audio.representation.id)}<br>${getCodec(audio.representation)}<br>`; infoElement.innerHTML = secureHTML; } } function showDebug(player, videoElement) { var secureHTML = "<style>\n#cp--debug-infos {\n position: absolute;\n top: " + escape(videoElement.offsetTop + 10) + "px;\n left: " + escape(videoElement.offsetLeft + 10) + "px;\n width: 500px;\n height: 300px;\n background-color: rgba(10, 10, 10, 0.83);\n overflow: hidden;\n color: white;\n text-align: left;\n padding: 2em;\n box-sizing: border-box;\n}\n#cp--debug-hide-infos {\n float: right;\n cursor: pointer;\n}\n</style>\n<div id=\"cp--debug-infos\">\n <a id=\"cp--debug-hide-infos\">[x]</a>\n <p id=\"cp--debug-infos-content\"></p>\n</div>"; var videoParent = videoElement.parentNode; var container = videoParent.querySelector("#cp--debug-infos-container"); if (!container) { container = document.createElement("div"); container.setAttribute("id", "cp--debug-infos-container"); videoParent.appendChild(container); } container.innerHTML = secureHTML; if (!closeBtn) { closeBtn = videoParent.querySelector("#cp--debug-hide-infos"); closeBtn.addEventListener("click", function () { return hideDebug(videoElement); }); } if (interval) clearInterval(interval); interval = setInterval(function () { return update(player, videoElement); }, 1000); update(player, videoElement); } function hideDebug(videoElement) { var container = videoElement.parentNode.querySelector("#cp--debug-infos-container"); if (container) { container.parentNode.removeChild(container); } if (interval) { clearInterval(interval); interval = null; } if (closeBtn) { closeBtn.removeEventListener("click", hideDebug); closeBtn = null; } } function toggleDebug(player, videoElement) { var container = videoElement.parentNode.querySelector("#cp--debug-infos-container"); if (container) { hideDebug(videoElement); } else { showDebug(player, videoElement); } } module.exports = { getDebug: getDebug, showDebug: showDebug, hideDebug: hideDebug, toggleDebug: toggleDebug }; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(process, global, module) {/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.1 */ (function() { "use strict"; function $$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function $$utils$$isFunction(x) { return typeof x === 'function'; } function $$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var $$utils$$_isArray; if (!Array.isArray) { $$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { $$utils$$_isArray = Array.isArray; } var $$utils$$isArray = $$utils$$_isArray; var $$utils$$now = Date.now || function() { return new Date().getTime(); }; function $$utils$$F() { } var $$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } $$utils$$F.prototype = o; return new $$utils$$F(); }); var $$asap$$len = 0; var $$asap$$default = function asap(callback, arg) { $$asap$$queue[$$asap$$len] = callback; $$asap$$queue[$$asap$$len + 1] = arg; $$asap$$len += 2; if ($$asap$$len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. $$asap$$scheduleFlush(); } }; var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver; // test for web worker but not in IE10 var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function $$asap$$useNextTick() { return function() { process.nextTick($$asap$$flush); }; } function $$asap$$useMutationObserver() { var iterations = 0; var observer = new $$asap$$BrowserMutationObserver($$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function $$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = $$asap$$flush; return function () { channel.port2.postMessage(0); }; } function $$asap$$useSetTimeout() { return function() { setTimeout($$asap$$flush, 1); }; } var $$asap$$queue = new Array(1000); function $$asap$$flush() { for (var i = 0; i < $$asap$$len; i+=2) { var callback = $$asap$$queue[i]; var arg = $$asap$$queue[i+1]; callback(arg); $$asap$$queue[i] = undefined; $$asap$$queue[i+1] = undefined; } $$asap$$len = 0; } var $$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { $$asap$$scheduleFlush = $$asap$$useNextTick(); } else if ($$asap$$BrowserMutationObserver) { $$asap$$scheduleFlush = $$asap$$useMutationObserver(); } else if ($$asap$$isWorker) { $$asap$$scheduleFlush = $$asap$$useMessageChannel(); } else { $$asap$$scheduleFlush = $$asap$$useSetTimeout(); } function $$$internal$$noop() {} var $$$internal$$PENDING = void 0; var $$$internal$$FULFILLED = 1; var $$$internal$$REJECTED = 2; var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$selfFullfillment() { return new TypeError("You cannot resolve a promise with itself"); } function $$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.') } function $$$internal$$getThen(promise) { try { return promise.then; } catch(error) { $$$internal$$GET_THEN_ERROR.error = error; return $$$internal$$GET_THEN_ERROR; } } function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function $$$internal$$handleForeignThenable(promise, thenable, then) { $$asap$$default(function(promise) { var sealed = false; var error = $$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { $$$internal$$resolve(promise, value); } else { $$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; $$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; $$$internal$$reject(promise, error); } }, promise); } function $$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, thenable._result); } else if (promise._state === $$$internal$$REJECTED) { $$$internal$$reject(promise, thenable._result); } else { $$$internal$$subscribe(thenable, undefined, function(value) { $$$internal$$resolve(promise, value); }, function(reason) { $$$internal$$reject(promise, reason); }); } } function $$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { $$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = $$$internal$$getThen(maybeThenable); if (then === $$$internal$$GET_THEN_ERROR) { $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { $$$internal$$fulfill(promise, maybeThenable); } else if ($$utils$$isFunction(then)) { $$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { $$$internal$$fulfill(promise, maybeThenable); } } } function $$$internal$$resolve(promise, value) { if (promise === value) { $$$internal$$reject(promise, $$$internal$$selfFullfillment()); } else if ($$utils$$objectOrFunction(value)) { $$$internal$$handleMaybeThenable(promise, value); } else { $$$internal$$fulfill(promise, value); } } function $$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } $$$internal$$publish(promise); } function $$$internal$$fulfill(promise, value) { if (promise._state !== $$$internal$$PENDING) { return; } promise._result = value; promise._state = $$$internal$$FULFILLED; if (promise._subscribers.length === 0) { } else { $$asap$$default($$$internal$$publish, promise); } } function $$$internal$$reject(promise, reason) { if (promise._state !== $$$internal$$PENDING) { return; } promise._state = $$$internal$$REJECTED; promise._result = reason; $$asap$$default($$$internal$$publishRejection, promise); } function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + $$$internal$$FULFILLED] = onFulfillment; subscribers[length + $$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { $$asap$$default($$$internal$$publish, parent); } } function $$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { $$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function $$$internal$$ErrorObject() { this.error = null; } var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { $$$internal$$TRY_CATCH_ERROR.error = e; return $$$internal$$TRY_CATCH_ERROR; } } function $$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = $$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = $$$internal$$tryCatch(callback, detail); if (value === $$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { $$$internal$$reject(promise, $$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== $$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { $$$internal$$resolve(promise, value); } else if (failed) { $$$internal$$reject(promise, error); } else if (settled === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, value); } else if (settled === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } } function $$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ $$$internal$$resolve(promise, value); }, function rejectPromise(reason) { $$$internal$$reject(promise, reason); }); } catch(e) { $$$internal$$reject(promise, e); } } function $$$enumerator$$makeSettledResult(state, position, value) { if (state === $$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor($$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { $$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { $$$internal$$fulfill(this.promise, this._result); } } } else { $$$internal$$reject(this.promise, this._validationError()); } } $$$enumerator$$Enumerator.prototype._validateInput = function(input) { return $$utils$$isArray(input); }; $$$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; $$$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var $$$enumerator$$default = $$$enumerator$$Enumerator; $$$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if ($$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { entry._onerror = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); } }; $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === $$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { $$$internal$$fulfill(promise, this._result); } }; $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; $$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt($$$internal$$REJECTED, i, reason); }); }; var $$promise$all$$default = function all(entries, label) { return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; var $$promise$race$$default = function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); if (!$$utils$$isArray(entries)) { $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { $$$internal$$resolve(promise, value); } function onRejection(reason) { $$$internal$$reject(promise, reason); } for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; }; var $$promise$resolve$$default = function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor($$$internal$$noop, label); $$$internal$$resolve(promise, object); return promise; }; var $$promise$reject$$default = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); $$$internal$$reject(promise, reason); return promise; }; var $$es6$promise$promise$$counter = 0; function $$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function $$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function $$es6$promise$promise$$Promise(resolver) { this._id = $$es6$promise$promise$$counter++; this._state = undefined; this._result = undefined; this._subscribers = []; if ($$$internal$$noop !== resolver) { if (!$$utils$$isFunction(resolver)) { $$es6$promise$promise$$needsResolver(); } if (!(this instanceof $$es6$promise$promise$$Promise)) { $$es6$promise$promise$$needsNew(); } $$$internal$$initializePromise(this, resolver); } } $$es6$promise$promise$$Promise.all = $$promise$all$$default; $$es6$promise$promise$$Promise.race = $$promise$race$$default; $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default; $$es6$promise$promise$$Promise.reject = $$promise$reject$$default; $$es6$promise$promise$$Promise.prototype = { constructor: $$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection) { var parent = this; var state = parent._state; if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { return this; } var child = new this.constructor($$$internal$$noop); var result = parent._result; if (state) { var callback = arguments[state - 1]; $$asap$$default(function(){ $$$internal$$invokeCallback(state, child, callback, result); }); } else { $$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function(onRejection) { return this.then(null, onRejection); } }; var $$es6$promise$polyfill$$default = function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return $$utils$$isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = $$es6$promise$promise$$default; } }; var es6$promise$umd$$ES6Promise = { 'Promise': $$es6$promise$promise$$default, 'polyfill': $$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if ("function" === 'function' && __webpack_require__(49)['amd']) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return es6$promise$umd$$ES6Promise; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = es6$promise$umd$$ES6Promise; } }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(15), (function() { return this; }()), __webpack_require__(22)(module))) /***/ }, /* 49 */ /***/ function(module, exports) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ } /******/ ]) }); ;
test/setup.js
vladovidiu/soundcloud
import React from 'react'; import { expect } from 'chai'; import jsdom from 'jsdom'; const doc = jsdom.jsdom('<!doctype html><html><body></body></html>'); const win = doc.defaultView; global.document = doc; global.window = win; Object.keys(window).forEach((key) => { if (!(key in global)) { global[key] = window[key]; } }); global.React = React; global.expect = expect;
ajax/libs/material-ui/5.0.0-alpha.30/modern/ImageList/ImageListContext.js
cdnjs/cdnjs
import * as React from 'react'; /** * @ignore - internal component. * @type {React.Context<{} | {expanded: boolean, disabled: boolean, toggle: () => void}>} */ const ImageListContext = /*#__PURE__*/React.createContext({}); if (process.env.NODE_ENV !== 'production') { ImageListContext.displayName = 'ImageListContext'; } export default ImageListContext;
examples/huge-apps/components/Dashboard.js
kurayama/react-router
import React from 'react' import { Link } from 'react-router' class Dashboard extends React.Component { render() { const { courses } = this.props return ( <div> <h2>Super Scalable Apps</h2> <p> Open the network tab as you navigate. Notice that only the amount of your app that is required is actually downloaded as you navigate around. Even the route configuration objects are loaded on the fly. This way, a new route added deep in your app will not affect the initial bundle of your application. </p> <h2>Courses</h2>{' '} <ul> {courses.map(course => ( <li key={course.id}> <Link to={`/course/${course.id}`}>{course.name}</Link> </li> ))} </ul> </div> ) } } export default Dashboard
app/javascript/mastodon/features/ui/components/report_modal.js
dwango/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { changeReportComment, changeReportForward, submitReport } from '../../../actions/reports'; import { expandAccountTimeline } from '../../../actions/timelines'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { makeGetAccount } from '../../../selectors'; import { defineMessages, FormattedMessage, injectIntl } from 'react-intl'; import StatusCheckBox from '../../report/containers/status_check_box_container'; import { OrderedSet } from 'immutable'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Button from '../../../components/button'; import Toggle from 'react-toggle'; import IconButton from '../../../components/icon_button'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, placeholder: { id: 'report.placeholder', defaultMessage: 'Additional comments' }, submit: { id: 'report.submit', defaultMessage: 'Submit' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = state => { const accountId = state.getIn(['reports', 'new', 'account_id']); return { isSubmitting: state.getIn(['reports', 'new', 'isSubmitting']), account: getAccount(state, accountId), comment: state.getIn(['reports', 'new', 'comment']), forward: state.getIn(['reports', 'new', 'forward']), statusIds: OrderedSet(state.getIn(['timelines', `account:${accountId}:with_replies`, 'items'])).union(state.getIn(['reports', 'new', 'status_ids'])), }; }; return mapStateToProps; }; export default @connect(makeMapStateToProps) @injectIntl class ReportModal extends ImmutablePureComponent { static propTypes = { isSubmitting: PropTypes.bool, account: ImmutablePropTypes.map, statusIds: ImmutablePropTypes.orderedSet.isRequired, comment: PropTypes.string.isRequired, forward: PropTypes.bool, dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleCommentChange = e => { this.props.dispatch(changeReportComment(e.target.value)); } handleForwardChange = e => { this.props.dispatch(changeReportForward(e.target.checked)); } handleSubmit = () => { this.props.dispatch(submitReport()); } handleKeyDown = e => { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { this.handleSubmit(); } } componentDidMount () { this.props.dispatch(expandAccountTimeline(this.props.account.get('id'), { withReplies: true })); } componentWillReceiveProps (nextProps) { if (this.props.account !== nextProps.account && nextProps.account) { this.props.dispatch(expandAccountTimeline(nextProps.account.get('id'), { withReplies: true })); } } render () { const { account, comment, intl, statusIds, isSubmitting, forward, onClose } = this.props; if (!account) { return null; } const domain = account.get('acct').split('@')[1]; return ( <div className='modal-root__modal report-modal'> <div className='report-modal__target'> <IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={16} /> <FormattedMessage id='report.target' defaultMessage='Report {target}' values={{ target: <strong>{account.get('acct')}</strong> }} /> </div> <div className='report-modal__container'> <div className='report-modal__comment'> <p><FormattedMessage id='report.hint' defaultMessage='The report will be sent to your instance moderators. You can provide an explanation of why you are reporting this account below:' /></p> <textarea className='setting-text light' placeholder={intl.formatMessage(messages.placeholder)} value={comment} onChange={this.handleCommentChange} onKeyDown={this.handleKeyDown} disabled={isSubmitting} autoFocus /> {domain && ( <div> <p><FormattedMessage id='report.forward_hint' defaultMessage='The account is from another server. Send an anonymized copy of the report there as well?' /></p> <div className='setting-toggle'> <Toggle id='report-forward' checked={forward} disabled={isSubmitting} onChange={this.handleForwardChange} /> <label htmlFor='report-forward' className='setting-toggle__label'><FormattedMessage id='report.forward' defaultMessage='Forward to {target}' values={{ target: domain }} /></label> </div> </div> )} <Button disabled={isSubmitting} text={intl.formatMessage(messages.submit)} onClick={this.handleSubmit} /> </div> <div className='report-modal__statuses'> <div> {statusIds.map(statusId => <StatusCheckBox id={statusId} key={statusId} disabled={isSubmitting} />)} </div> </div> </div> </div> ); } }
app/containers/PlacesPage/index.js
joeysherman/noodle-time
/* * * PlacesPage * */ // Dependencies import React from 'react'; import { connect } from 'react-redux'; import { compose } from 'redux'; import injectSaga from 'utils/injectSaga'; import saga from './saga'; import reducer from './reducer'; import { push } from 'connected-react-router'; import { Link } from 'react-router-dom'; import queryString from 'query-string'; // Redux imports import { placesRequest } from './actions'; import { userLocationRequest } from '../App/actions'; import { incPlacesIndex, decPlacesIndex, setPlacesIndex, detailRequest, } from './actions'; import { selectLoadingGeo } from '../App/selectors'; import { selectPlaces, selectDetailById, selectPlacesLoading, } from './selectors'; // Component imports import Map from '../Map'; import List from '../../components/List'; import ListItem from '../../components/ListItem'; import LoadingSpinner from '../../components/LoadingSpinner'; import Card from '../../components/Card'; import Review from '../../components/Review'; import ActionBar from '../../components/ActionBar'; import { Trail } from 'react-spring/renderprops'; import { incrementIndex, decrementIndex } from './actions'; import { selectIndex } from './selectors'; import { selectLocation } from '../App/selectors'; import { SET_SELECTED_INDEX } from './constants'; import PulsingRamen from '../../components/PulsingRamen/pulsingRamen'; export class PlacesPage extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { showMap: window.innerWidth >= 768 }; } componentDidMount() { if (typeof this.props.userLocation === 'boolean') { this.props.fetchLocation(); } else { this.fetchPlaces(); } } componentDidUpdate(prevProps, prevState, prevContext) { if ( prevProps.userLocation.error == undefined && this.props.userLocation.error ) { console.log('error in geolocation'); } if (prevProps.loadingLocation && !this.props.loadingLocation) { this.fetchPlaces(); } } componentWillUnmount() {} componentWillMount() { if (window.innerWidth >= 768) { } } fetchPlaces = () => { let { latitude, longitude } = this.props.userLocation; this.props.fetchPlaces({ latitude, longitude, }); }; locationValid = () => { let { geometry } = this.props.userLocation; if (!geometry) return false; let { location: { lat, lng }, } = geometry; let latitude = parseInt(lat), longitude = parseInt(lng); if (!(Number.isInteger(latitude) && Number.isInteger(longitude))) return false; return ( latitude < 90 && latitude > -90 && longitude < 180 && longitude > -180 ); }; renderCardView = () => { let placeData = this.props.places[this.props.index]; let loading = this.props.loading === 'details'; let detailData = this.props.detail; let reviewsObject = detailData && detailData.reviews; let details = detailData && detailData.detail; return ( <div className="w-full md:w-3/5"> <Card place={placeData} detail={details} loading={loading}> {reviewsObject ? ( <Trail keys={item => item.id} items={reviewsObject.reviews} from={{ opacity: 0, transform: 'translate3d(-40px,0,0)' }} to={{ opacity: 1, transform: 'translate3d(0,0px,0)' }} delay={100} > {item => props => <Review data={item} style={props} />} </Trail> ) : ( <LoadingSpinner /> )} </Card> </div> ); }; handleListItemClick = ({ id, index }) => { this.props.history.push({ pathname: '/places', search: `?detail=${id}`, }); this.props.fetchDetail(id); this.props.setIndex(index); }; renderListItems = places => { return places.map((place, i) => ( <ListItem key={i} place={place} index={i + 1} onClick={this.handleListItemClick.bind(this, { id: place.id, index: i, })} /> )); }; showList = () => { this.props.setIndex(false); }; renderList = () => { if (this.props.places.length) { console.log('inside renderlist'); let { places } = this.props; let count = places.length; let placesToRender = places.slice(0, count >= 5 ? 5 : count); let items = this.renderListItems(placesToRender); return ( <div className="w-full md:w-3/5 bg-white rounded shadow-md"> <Trail items={items} keys={item => item.key} from={{ opacity: 0, transform: 'translate3d(-20px,0px,0)' }} to={{ opacity: 1, transform: 'translate3d(0,0px,0)' }} delay={100} > {item => props => <div style={props}>{item}</div>} </Trail> </div> ); } else { console.log('no places'); return false; } }; renderBackButton = () => { return ( <Link to={{ pathname: "/places" }} className="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded"> Back </Link> ) } renderActionButton = () => { return ( <button className="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded"> Filter </button> ) } render() { const { loadingLocation, loading } = this.props; const length = this.props.places && this.props.places.length; const arrOfLoadingText = [ 'Simmering the broth..', 'Pulling the noodles..', 'Prepping the toppings..', 'Cutting the Nori..', 'Warming the bowl..', ]; const rand = Math.floor(Math.random() * 5); const loadingText = arrOfLoadingText[rand]; const index = this.props.index; const qs = queryString.parse(this.props.history.location.search); const showMap = this.state.showMap || (qs.mode && qs.mode == 'map'); const mapLink = { ...qs, mode: 'map', }; const showDetail = qs && qs.detail && length; return ( <div className="container mx-auto"> <ActionBar className="p-2 flex justify-between items-center bg-white"> {showDetail ? this.renderBackButton() : this.renderActionButton()} <div>{!showDetail && <h3>Showing {length} places near you.</h3>}</div> <div className="inline-flex"> <Link to={{ pathname: '/places', search: queryString.stringify(mapLink), }} className="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded-l" > Map </Link> <Link className="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded-r" to={{ pathname: '/places', }} > List </Link> </div> </ActionBar> <div className="flex flex-wrap flex-col-reverse md:flex-row md:flex-no-wrap"> {loadingLocation || (loading === 'places' && ( <div className="w-full md:w-3/5 text-center"> <h1 className="font-semibold leading-relaxed text-4xl mb-4"> {loadingText} </h1> <div className="flex justify-center"> <LoadingSpinner className="w-32" /> </div> </div> ))} {showDetail ? this.renderCardView() : this.renderList()} {showMap ? ( <Map classNames="w-full md:w-2/5 h-48 md:h-64 md:ml-8" /> ) : ( false )} </div> </div> ); } } const mapStateToProps = (state, ownProps) => ({ loadingLocation: selectLoadingGeo(state), loading: selectPlacesLoading(state), userLocation: selectLocation(state), places: selectPlaces(state), index: selectIndex(state), detail: selectDetailById( state, queryString.parse(ownProps.history.location.search), ), }); function mapDispatchToProps(dispatch, ownProps) { return { fetchLocation: () => dispatch(userLocationRequest()), fetchPlaces: location => dispatch(placesRequest(location)), fetchDetail: id => dispatch(detailRequest(id)), incIndex: () => dispatch(incPlacesIndex()), decIndex: () => dispatch(decPlacesIndex()), setIndex: index => dispatch(setPlacesIndex(index)), goTo: location => dispatch(push(location)), dispatch, }; } const withConnect = connect( mapStateToProps, mapDispatchToProps, ); const withSaga = injectSaga({ key: 'places', saga }); export default compose( withConnect, withSaga, )(PlacesPage);
ajax/libs/IndexedDBShim/3.0.0-rc.3/indexeddbshim-noninvasive.js
joeyparrish/cdnjs
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.setGlobalVars = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (global){ "use strict"; require("core-js/shim"); require("regenerator-runtime/runtime"); require("core-js/fn/regexp/escape"); if (global._babelPolyfill) { throw new Error("only one instance of babel-polyfill is allowed"); } global._babelPolyfill = true; var DEFINE_PROPERTY = "defineProperty"; function define(O, key, value) { O[key] || Object[DEFINE_PROPERTY](O, key, { writable: true, configurable: true, value: value }); } define(String.prototype, "padLeft", "".padStart); define(String.prototype, "padRight", "".padEnd); "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { [][key] && define(Array, key, Function.call.bind([][key])); }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"core-js/fn/regexp/escape":4,"core-js/shim":297,"regenerator-runtime/runtime":301}],2:[function(require,module,exports){ /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function(){ "use strict"; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Use a lookup table to find the index. var lookup = new Uint8Array(256); for (var i = 0; i < chars.length; i++) { lookup[chars.charCodeAt(i)] = i; } exports.encode = function(arraybuffer, offset, length) { var bytes = new Uint8Array(arraybuffer, offset || 0, length !== undefined ? length : arraybuffer.byteLength), i, len = bytes.length, base64 = ""; for (i = 0; i < len; i+=3) { base64 += chars[bytes[i] >> 2]; base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64 += chars[bytes[i + 2] & 63]; } if ((len % 3) === 2) { base64 = base64.substring(0, base64.length - 1) + "="; } else if (len % 3 === 1) { base64 = base64.substring(0, base64.length - 2) + "=="; } return base64; }; exports.decode = function(base64) { var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; if (base64[base64.length - 1] === "=") { bufferLength--; if (base64[base64.length - 2] === "=") { bufferLength--; } } var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); for (i = 0; i < len; i+=4) { encoded1 = lookup[base64.charCodeAt(i)]; encoded2 = lookup[base64.charCodeAt(i+1)]; encoded3 = lookup[base64.charCodeAt(i+2)]; encoded4 = lookup[base64.charCodeAt(i+3)]; bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return arraybuffer; }; })(); },{}],3:[function(require,module,exports){ },{}],4:[function(require,module,exports){ require('../../modules/core.regexp.escape'); module.exports = require('../../modules/_core').RegExp.escape; },{"../../modules/_core":25,"../../modules/core.regexp.escape":121}],5:[function(require,module,exports){ module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; },{}],6:[function(require,module,exports){ var cof = require('./_cof'); module.exports = function(it, msg){ if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg); return +it; }; },{"./_cof":20}],7:[function(require,module,exports){ // 22.1.3.31 Array.prototype[@@unscopables] var UNSCOPABLES = require('./_wks')('unscopables') , ArrayProto = Array.prototype; if(ArrayProto[UNSCOPABLES] == undefined)require('./_hide')(ArrayProto, UNSCOPABLES, {}); module.exports = function(key){ ArrayProto[UNSCOPABLES][key] = true; }; },{"./_hide":42,"./_wks":119}],8:[function(require,module,exports){ module.exports = function(it, Constructor, name, forbiddenField){ if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ throw TypeError(name + ': incorrect invocation!'); } return it; }; },{}],9:[function(require,module,exports){ var isObject = require('./_is-object'); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; },{"./_is-object":51}],10:[function(require,module,exports){ // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) 'use strict'; var toObject = require('./_to-object') , toIndex = require('./_to-index') , toLength = require('./_to-length'); module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){ var O = toObject(this) , len = toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments.length > 2 ? arguments[2] : undefined , count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from += count - 1; to += count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; }; },{"./_to-index":107,"./_to-length":110,"./_to-object":111}],11:[function(require,module,exports){ // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) 'use strict'; var toObject = require('./_to-object') , toIndex = require('./_to-index') , toLength = require('./_to-length'); module.exports = function fill(value /*, start = 0, end = @length */){ var O = toObject(this) , length = toLength(O.length) , aLen = arguments.length , index = toIndex(aLen > 1 ? arguments[1] : undefined, length) , end = aLen > 2 ? arguments[2] : undefined , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; }; },{"./_to-index":107,"./_to-length":110,"./_to-object":111}],12:[function(require,module,exports){ var forOf = require('./_for-of'); module.exports = function(iter, ITERATOR){ var result = []; forOf(iter, false, result.push, result, ITERATOR); return result; }; },{"./_for-of":39}],13:[function(require,module,exports){ // false -> Array#indexOf // true -> Array#includes var toIObject = require('./_to-iobject') , toLength = require('./_to-length') , toIndex = require('./_to-index'); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; },{"./_to-index":107,"./_to-iobject":109,"./_to-length":110}],14:[function(require,module,exports){ // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var ctx = require('./_ctx') , IObject = require('./_iobject') , toObject = require('./_to-object') , toLength = require('./_to-length') , asc = require('./_array-species-create'); module.exports = function(TYPE, $create){ var IS_MAP = TYPE == 1 , IS_FILTER = TYPE == 2 , IS_SOME = TYPE == 3 , IS_EVERY = TYPE == 4 , IS_FIND_INDEX = TYPE == 6 , NO_HOLES = TYPE == 5 || IS_FIND_INDEX , create = $create || asc; return function($this, callbackfn, that){ var O = toObject($this) , self = IObject(O) , f = ctx(callbackfn, that, 3) , length = toLength(self.length) , index = 0 , result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; },{"./_array-species-create":17,"./_ctx":27,"./_iobject":47,"./_to-length":110,"./_to-object":111}],15:[function(require,module,exports){ var aFunction = require('./_a-function') , toObject = require('./_to-object') , IObject = require('./_iobject') , toLength = require('./_to-length'); module.exports = function(that, callbackfn, aLen, memo, isRight){ aFunction(callbackfn); var O = toObject(that) , self = IObject(O) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(aLen < 2)for(;;){ if(index in self){ memo = self[index]; index += i; break; } index += i; if(isRight ? index < 0 : length <= index){ throw TypeError('Reduce of empty array with no initial value'); } } for(;isRight ? index >= 0 : length > index; index += i)if(index in self){ memo = callbackfn(memo, self[index], index, O); } return memo; }; },{"./_a-function":5,"./_iobject":47,"./_to-length":110,"./_to-object":111}],16:[function(require,module,exports){ var isObject = require('./_is-object') , isArray = require('./_is-array') , SPECIES = require('./_wks')('species'); module.exports = function(original){ var C; if(isArray(original)){ C = original.constructor; // cross-realm fallback if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined; if(isObject(C)){ C = C[SPECIES]; if(C === null)C = undefined; } } return C === undefined ? Array : C; }; },{"./_is-array":49,"./_is-object":51,"./_wks":119}],17:[function(require,module,exports){ // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var speciesConstructor = require('./_array-species-constructor'); module.exports = function(original, length){ return new (speciesConstructor(original))(length); }; },{"./_array-species-constructor":16}],18:[function(require,module,exports){ 'use strict'; var aFunction = require('./_a-function') , isObject = require('./_is-object') , invoke = require('./_invoke') , arraySlice = [].slice , factories = {}; var construct = function(F, len, args){ if(!(len in factories)){ for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']'; factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); } return factories[len](F, args); }; module.exports = Function.bind || function bind(that /*, args... */){ var fn = aFunction(this) , partArgs = arraySlice.call(arguments, 1); var bound = function(/* args... */){ var args = partArgs.concat(arraySlice.call(arguments)); return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); }; if(isObject(fn.prototype))bound.prototype = fn.prototype; return bound; }; },{"./_a-function":5,"./_invoke":46,"./_is-object":51}],19:[function(require,module,exports){ // getting tag from 19.1.3.6 Object.prototype.toString() var cof = require('./_cof') , TAG = require('./_wks')('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; },{"./_cof":20,"./_wks":119}],20:[function(require,module,exports){ var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; },{}],21:[function(require,module,exports){ 'use strict'; var dP = require('./_object-dp').f , create = require('./_object-create') , redefineAll = require('./_redefine-all') , ctx = require('./_ctx') , anInstance = require('./_an-instance') , defined = require('./_defined') , forOf = require('./_for-of') , $iterDefine = require('./_iter-define') , step = require('./_iter-step') , setSpecies = require('./_set-species') , DESCRIPTORS = require('./_descriptors') , fastKey = require('./_meta').fastKey , SIZE = DESCRIPTORS ? '_s' : 'size'; var getEntry = function(that, key){ // fast case var index = fastKey(key), entry; if(index !== 'F')return that._i[index]; // frozen object case for(entry = that._f; entry; entry = entry.n){ if(entry.k == key)return entry; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ anInstance(that, C, NAME, '_i'); that._i = create(null); // index that._f = undefined; // first entry that._l = undefined; // last entry that[SIZE] = 0; // size if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear(){ for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that._f = that._l = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that._i[entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that._f == entry)that._f = next; if(that._l == entry)that._l = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /*, that = undefined */){ anInstance(this, C, 'forEach'); var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3) , entry; while(entry = entry ? entry.n : this._f){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key){ return !!getEntry(this, key); } }); if(DESCRIPTORS)dP(C.prototype, 'size', { get: function(){ return defined(this[SIZE]); } }); return C; }, def: function(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry){ entry.v = value; // create new entry } else { that._l = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that._l, // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that._f)that._f = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index !== 'F')that._i[index] = entry; } return that; }, getEntry: getEntry, setStrong: function(C, NAME, IS_MAP){ // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 $iterDefine(C, NAME, function(iterated, kind){ this._t = iterated; // target this._k = kind; // kind this._l = undefined; // previous }, function(){ var that = this , kind = that._k , entry = that._l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){ // or finish the iteration that._t = undefined; return step(1); } // return step by kind if(kind == 'keys' )return step(0, entry.k); if(kind == 'values')return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2 setSpecies(NAME); } }; },{"./_an-instance":8,"./_ctx":27,"./_defined":29,"./_descriptors":30,"./_for-of":39,"./_iter-define":55,"./_iter-step":57,"./_meta":64,"./_object-create":68,"./_object-dp":69,"./_redefine-all":88,"./_set-species":93}],22:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var classof = require('./_classof') , from = require('./_array-from-iterable'); module.exports = function(NAME){ return function toJSON(){ if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic"); return from(this); }; }; },{"./_array-from-iterable":12,"./_classof":19}],23:[function(require,module,exports){ 'use strict'; var redefineAll = require('./_redefine-all') , getWeak = require('./_meta').getWeak , anObject = require('./_an-object') , isObject = require('./_is-object') , anInstance = require('./_an-instance') , forOf = require('./_for-of') , createArrayMethod = require('./_array-methods') , $has = require('./_has') , arrayFind = createArrayMethod(5) , arrayFindIndex = createArrayMethod(6) , id = 0; // fallback for uncaught frozen keys var uncaughtFrozenStore = function(that){ return that._l || (that._l = new UncaughtFrozenStore); }; var UncaughtFrozenStore = function(){ this.a = []; }; var findUncaughtFrozen = function(store, key){ return arrayFind(store.a, function(it){ return it[0] === key; }); }; UncaughtFrozenStore.prototype = { get: function(key){ var entry = findUncaughtFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findUncaughtFrozen(this, key); }, set: function(key, value){ var entry = findUncaughtFrozen(this, key); if(entry)entry[1] = value; else this.a.push([key, value]); }, 'delete': function(key){ var index = arrayFindIndex(this.a, function(it){ return it[0] === key; }); if(~index)this.a.splice(index, 1); return !!~index; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ anInstance(that, C, NAME, '_i'); that._i = id++; // collection id that._l = undefined; // leak store for uncaught frozen objects if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this)['delete'](key); return data && $has(data, this._i) && delete data[this._i]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).has(key); return data && $has(data, this._i); } }); return C; }, def: function(that, key, value){ var data = getWeak(anObject(key), true); if(data === true)uncaughtFrozenStore(that).set(key, value); else data[that._i] = value; return that; }, ufstore: uncaughtFrozenStore }; },{"./_an-instance":8,"./_an-object":9,"./_array-methods":14,"./_for-of":39,"./_has":41,"./_is-object":51,"./_meta":64,"./_redefine-all":88}],24:[function(require,module,exports){ 'use strict'; var global = require('./_global') , $export = require('./_export') , redefine = require('./_redefine') , redefineAll = require('./_redefine-all') , meta = require('./_meta') , forOf = require('./_for-of') , anInstance = require('./_an-instance') , isObject = require('./_is-object') , fails = require('./_fails') , $iterDetect = require('./_iter-detect') , setToStringTag = require('./_set-to-string-tag') , inheritIfRequired = require('./_inherit-if-required'); module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ var Base = global[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; var fixMethod = function(KEY){ var fn = proto[KEY]; redefine(proto, KEY, KEY == 'delete' ? function(a){ return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); } : KEY == 'has' ? function has(a){ return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); } : KEY == 'get' ? function get(a){ return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); } : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; } : function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; } ); }; if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){ new C().entries().next(); }))){ // create collection constructor C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); redefineAll(C.prototype, methods); meta.NEED = true; } else { var instance = new C // early implementations not supports chaining , HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false , THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); }) // most early implementations doesn't supports iterables, most modern - not close it correctly , ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new // for early implementations -0 and +0 not the same , BUGGY_ZERO = !IS_WEAK && fails(function(){ // V8 ~ Chromium 42- fails only with 5+ elements var $instance = new C() , index = 5; while(index--)$instance[ADDER](index, index); return !$instance.has(-0); }); if(!ACCEPT_ITERABLES){ C = wrapper(function(target, iterable){ anInstance(target, C, NAME); var that = inheritIfRequired(new Base, target, C); if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); return that; }); C.prototype = proto; proto.constructor = C; } if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){ fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER); // weak collections should not contains .clear method if(IS_WEAK && proto.clear)delete proto.clear; } setToStringTag(C, NAME); O[NAME] = C; $export($export.G + $export.W + $export.F * (C != Base), O); if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); return C; }; },{"./_an-instance":8,"./_export":34,"./_fails":36,"./_for-of":39,"./_global":40,"./_inherit-if-required":45,"./_is-object":51,"./_iter-detect":56,"./_meta":64,"./_redefine":89,"./_redefine-all":88,"./_set-to-string-tag":94}],25:[function(require,module,exports){ var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef },{}],26:[function(require,module,exports){ 'use strict'; var $defineProperty = require('./_object-dp') , createDesc = require('./_property-desc'); module.exports = function(object, index, value){ if(index in object)$defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; },{"./_object-dp":69,"./_property-desc":87}],27:[function(require,module,exports){ // optional / simple context binding var aFunction = require('./_a-function'); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; },{"./_a-function":5}],28:[function(require,module,exports){ 'use strict'; var anObject = require('./_an-object') , toPrimitive = require('./_to-primitive') , NUMBER = 'number'; module.exports = function(hint){ if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint'); return toPrimitive(anObject(this), hint != NUMBER); }; },{"./_an-object":9,"./_to-primitive":112}],29:[function(require,module,exports){ // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; },{}],30:[function(require,module,exports){ // Thank's IE8 for his funny defineProperty module.exports = !require('./_fails')(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); },{"./_fails":36}],31:[function(require,module,exports){ var isObject = require('./_is-object') , document = require('./_global').document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; },{"./_global":40,"./_is-object":51}],32:[function(require,module,exports){ // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); },{}],33:[function(require,module,exports){ // all enumerable object keys, includes symbols var getKeys = require('./_object-keys') , gOPS = require('./_object-gops') , pIE = require('./_object-pie'); module.exports = function(it){ var result = getKeys(it) , getSymbols = gOPS.f; if(getSymbols){ var symbols = getSymbols(it) , isEnum = pIE.f , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); } return result; }; },{"./_object-gops":75,"./_object-keys":78,"./_object-pie":79}],34:[function(require,module,exports){ var global = require('./_global') , core = require('./_core') , hide = require('./_hide') , redefine = require('./_redefine') , ctx = require('./_ctx') , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE] , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}) , key, own, out, exp; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // extend global if(target)redefine(target, key, out, type & $export.U); // export if(exports[key] != out)hide(exports, key, exp); if(IS_PROTO && expProto[key] != out)expProto[key] = out; } }; global.core = core; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; },{"./_core":25,"./_ctx":27,"./_global":40,"./_hide":42,"./_redefine":89}],35:[function(require,module,exports){ var MATCH = require('./_wks')('match'); module.exports = function(KEY){ var re = /./; try { '/./'[KEY](re); } catch(e){ try { re[MATCH] = false; return !'/./'[KEY](re); } catch(f){ /* empty */ } } return true; }; },{"./_wks":119}],36:[function(require,module,exports){ module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; },{}],37:[function(require,module,exports){ 'use strict'; var hide = require('./_hide') , redefine = require('./_redefine') , fails = require('./_fails') , defined = require('./_defined') , wks = require('./_wks'); module.exports = function(KEY, length, exec){ var SYMBOL = wks(KEY) , fns = exec(defined, SYMBOL, ''[KEY]) , strfn = fns[0] , rxfn = fns[1]; if(fails(function(){ var O = {}; O[SYMBOL] = function(){ return 7; }; return ''[KEY](O) != 7; })){ redefine(String.prototype, KEY, strfn); hide(RegExp.prototype, SYMBOL, length == 2 // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) // 21.2.5.11 RegExp.prototype[@@split](string, limit) ? function(string, arg){ return rxfn.call(string, this, arg); } // 21.2.5.6 RegExp.prototype[@@match](string) // 21.2.5.9 RegExp.prototype[@@search](string) : function(string){ return rxfn.call(string, this); } ); } }; },{"./_defined":29,"./_fails":36,"./_hide":42,"./_redefine":89,"./_wks":119}],38:[function(require,module,exports){ 'use strict'; // 21.2.5.3 get RegExp.prototype.flags var anObject = require('./_an-object'); module.exports = function(){ var that = anObject(this) , result = ''; if(that.global) result += 'g'; if(that.ignoreCase) result += 'i'; if(that.multiline) result += 'm'; if(that.unicode) result += 'u'; if(that.sticky) result += 'y'; return result; }; },{"./_an-object":9}],39:[function(require,module,exports){ var ctx = require('./_ctx') , call = require('./_iter-call') , isArrayIter = require('./_is-array-iter') , anObject = require('./_an-object') , toLength = require('./_to-length') , getIterFn = require('./core.get-iterator-method') , BREAK = {} , RETURN = {}; var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable) , f = ctx(fn, that, entries ? 2 : 1) , index = 0 , length, step, iterator, result; if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if(result === BREAK || result === RETURN)return result; } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ result = call(iterator, f, step.value, entries); if(result === BREAK || result === RETURN)return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; },{"./_an-object":9,"./_ctx":27,"./_is-array-iter":48,"./_iter-call":53,"./_to-length":110,"./core.get-iterator-method":120}],40:[function(require,module,exports){ // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef },{}],41:[function(require,module,exports){ var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; },{}],42:[function(require,module,exports){ var dP = require('./_object-dp') , createDesc = require('./_property-desc'); module.exports = require('./_descriptors') ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; },{"./_descriptors":30,"./_object-dp":69,"./_property-desc":87}],43:[function(require,module,exports){ module.exports = require('./_global').document && document.documentElement; },{"./_global":40}],44:[function(require,module,exports){ module.exports = !require('./_descriptors') && !require('./_fails')(function(){ return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7; }); },{"./_descriptors":30,"./_dom-create":31,"./_fails":36}],45:[function(require,module,exports){ var isObject = require('./_is-object') , setPrototypeOf = require('./_set-proto').set; module.exports = function(that, target, C){ var P, S = target.constructor; if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){ setPrototypeOf(that, P); } return that; }; },{"./_is-object":51,"./_set-proto":92}],46:[function(require,module,exports){ // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; },{}],47:[function(require,module,exports){ // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = require('./_cof'); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; },{"./_cof":20}],48:[function(require,module,exports){ // check on default Array iterator var Iterators = require('./_iterators') , ITERATOR = require('./_wks')('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; },{"./_iterators":58,"./_wks":119}],49:[function(require,module,exports){ // 7.2.2 IsArray(argument) var cof = require('./_cof'); module.exports = Array.isArray || function isArray(arg){ return cof(arg) == 'Array'; }; },{"./_cof":20}],50:[function(require,module,exports){ // 20.1.2.3 Number.isInteger(number) var isObject = require('./_is-object') , floor = Math.floor; module.exports = function isInteger(it){ return !isObject(it) && isFinite(it) && floor(it) === it; }; },{"./_is-object":51}],51:[function(require,module,exports){ module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; },{}],52:[function(require,module,exports){ // 7.2.8 IsRegExp(argument) var isObject = require('./_is-object') , cof = require('./_cof') , MATCH = require('./_wks')('match'); module.exports = function(it){ var isRegExp; return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); }; },{"./_cof":20,"./_is-object":51,"./_wks":119}],53:[function(require,module,exports){ // call something on iterator step with safe closing on error var anObject = require('./_an-object'); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; },{"./_an-object":9}],54:[function(require,module,exports){ 'use strict'; var create = require('./_object-create') , descriptor = require('./_property-desc') , setToStringTag = require('./_set-to-string-tag') , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() require('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; },{"./_hide":42,"./_object-create":68,"./_property-desc":87,"./_set-to-string-tag":94,"./_wks":119}],55:[function(require,module,exports){ 'use strict'; var LIBRARY = require('./_library') , $export = require('./_export') , redefine = require('./_redefine') , hide = require('./_hide') , has = require('./_has') , Iterators = require('./_iterators') , $iterCreate = require('./_iter-create') , setToStringTag = require('./_set-to-string-tag') , getPrototypeOf = require('./_object-gpo') , ITERATOR = require('./_wks')('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; },{"./_export":34,"./_has":41,"./_hide":42,"./_iter-create":54,"./_iterators":58,"./_library":60,"./_object-gpo":76,"./_redefine":89,"./_set-to-string-tag":94,"./_wks":119}],56:[function(require,module,exports){ var ITERATOR = require('./_wks')('iterator') , SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR](); iter.next = function(){ return {done: safe = true}; }; arr[ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; },{"./_wks":119}],57:[function(require,module,exports){ module.exports = function(done, value){ return {value: value, done: !!done}; }; },{}],58:[function(require,module,exports){ module.exports = {}; },{}],59:[function(require,module,exports){ var getKeys = require('./_object-keys') , toIObject = require('./_to-iobject'); module.exports = function(object, el){ var O = toIObject(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; },{"./_object-keys":78,"./_to-iobject":109}],60:[function(require,module,exports){ module.exports = false; },{}],61:[function(require,module,exports){ // 20.2.2.14 Math.expm1(x) var $expm1 = Math.expm1; module.exports = (!$expm1 // Old FF bug || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 // Tor Browser bug || $expm1(-2e-17) != -2e-17 ) ? function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; } : $expm1; },{}],62:[function(require,module,exports){ // 20.2.2.20 Math.log1p(x) module.exports = Math.log1p || function log1p(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); }; },{}],63:[function(require,module,exports){ // 20.2.2.28 Math.sign(x) module.exports = Math.sign || function sign(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; }; },{}],64:[function(require,module,exports){ var META = require('./_uid')('meta') , isObject = require('./_is-object') , has = require('./_has') , setDesc = require('./_object-dp').f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !require('./_fails')(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ setDesc(it, META, {value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs }}); }; var fastKey = function(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return 'F'; // not necessary to add metadata if(!create)return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function(it, create){ if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return true; // not necessary to add metadata if(!create)return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function(it){ if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; },{"./_fails":36,"./_has":41,"./_is-object":51,"./_object-dp":69,"./_uid":116}],65:[function(require,module,exports){ var Map = require('./es6.map') , $export = require('./_export') , shared = require('./_shared')('metadata') , store = shared.store || (shared.store = new (require('./es6.weak-map'))); var getOrCreateMetadataMap = function(target, targetKey, create){ var targetMetadata = store.get(target); if(!targetMetadata){ if(!create)return undefined; store.set(target, targetMetadata = new Map); } var keyMetadata = targetMetadata.get(targetKey); if(!keyMetadata){ if(!create)return undefined; targetMetadata.set(targetKey, keyMetadata = new Map); } return keyMetadata; }; var ordinaryHasOwnMetadata = function(MetadataKey, O, P){ var metadataMap = getOrCreateMetadataMap(O, P, false); return metadataMap === undefined ? false : metadataMap.has(MetadataKey); }; var ordinaryGetOwnMetadata = function(MetadataKey, O, P){ var metadataMap = getOrCreateMetadataMap(O, P, false); return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); }; var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){ getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); }; var ordinaryOwnMetadataKeys = function(target, targetKey){ var metadataMap = getOrCreateMetadataMap(target, targetKey, false) , keys = []; if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); }); return keys; }; var toMetaKey = function(it){ return it === undefined || typeof it == 'symbol' ? it : String(it); }; var exp = function(O){ $export($export.S, 'Reflect', O); }; module.exports = { store: store, map: getOrCreateMetadataMap, has: ordinaryHasOwnMetadata, get: ordinaryGetOwnMetadata, set: ordinaryDefineOwnMetadata, keys: ordinaryOwnMetadataKeys, key: toMetaKey, exp: exp }; },{"./_export":34,"./_shared":96,"./es6.map":151,"./es6.weak-map":257}],66:[function(require,module,exports){ var global = require('./_global') , macrotask = require('./_task').set , Observer = global.MutationObserver || global.WebKitMutationObserver , process = global.process , Promise = global.Promise , isNode = require('./_cof')(process) == 'process'; module.exports = function(){ var head, last, notify; var flush = function(){ var parent, fn; if(isNode && (parent = process.domain))parent.exit(); while(head){ fn = head.fn; head = head.next; try { fn(); } catch(e){ if(head)notify(); else last = undefined; throw e; } } last = undefined; if(parent)parent.enter(); }; // Node.js if(isNode){ notify = function(){ process.nextTick(flush); }; // browsers with MutationObserver } else if(Observer){ var toggle = true , node = document.createTextNode(''); new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new notify = function(){ node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if(Promise && Promise.resolve){ var promise = Promise.resolve(); notify = function(){ promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function(){ // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } return function(fn){ var task = {fn: fn, next: undefined}; if(last)last.next = task; if(!head){ head = task; notify(); } last = task; }; }; },{"./_cof":20,"./_global":40,"./_task":106}],67:[function(require,module,exports){ 'use strict'; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = require('./_object-keys') , gOPS = require('./_object-gops') , pIE = require('./_object-pie') , toObject = require('./_to-object') , IObject = require('./_iobject') , $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || require('./_fails')(function(){ var A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , aLen = arguments.length , index = 1 , getSymbols = gOPS.f , isEnum = pIE.f; while(aLen > index){ var S = IObject(arguments[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : $assign; },{"./_fails":36,"./_iobject":47,"./_object-gops":75,"./_object-keys":78,"./_object-pie":79,"./_to-object":111}],68:[function(require,module,exports){ // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = require('./_an-object') , dPs = require('./_object-dps') , enumBugKeys = require('./_enum-bug-keys') , IE_PROTO = require('./_shared-key')('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = require('./_dom-create')('iframe') , i = enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; require('./_html').appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; },{"./_an-object":9,"./_dom-create":31,"./_enum-bug-keys":32,"./_html":43,"./_object-dps":70,"./_shared-key":95}],69:[function(require,module,exports){ var anObject = require('./_an-object') , IE8_DOM_DEFINE = require('./_ie8-dom-define') , toPrimitive = require('./_to-primitive') , dP = Object.defineProperty; exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; },{"./_an-object":9,"./_descriptors":30,"./_ie8-dom-define":44,"./_to-primitive":112}],70:[function(require,module,exports){ var dP = require('./_object-dp') , anObject = require('./_an-object') , getKeys = require('./_object-keys'); module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; },{"./_an-object":9,"./_descriptors":30,"./_object-dp":69,"./_object-keys":78}],71:[function(require,module,exports){ // Forced replacement prototype accessors methods module.exports = require('./_library')|| !require('./_fails')(function(){ var K = Math.random(); // In FF throws only define methods __defineSetter__.call(null, K, function(){ /* empty */}); delete require('./_global')[K]; }); },{"./_fails":36,"./_global":40,"./_library":60}],72:[function(require,module,exports){ var pIE = require('./_object-pie') , createDesc = require('./_property-desc') , toIObject = require('./_to-iobject') , toPrimitive = require('./_to-primitive') , has = require('./_has') , IE8_DOM_DEFINE = require('./_ie8-dom-define') , gOPD = Object.getOwnPropertyDescriptor; exports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P){ O = toIObject(O); P = toPrimitive(P, true); if(IE8_DOM_DEFINE)try { return gOPD(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); }; },{"./_descriptors":30,"./_has":41,"./_ie8-dom-define":44,"./_object-pie":79,"./_property-desc":87,"./_to-iobject":109,"./_to-primitive":112}],73:[function(require,module,exports){ // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = require('./_to-iobject') , gOPN = require('./_object-gopn').f , toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return gOPN(it); } catch(e){ return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it){ return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; },{"./_object-gopn":74,"./_to-iobject":109}],74:[function(require,module,exports){ // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = require('./_object-keys-internal') , hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return $keys(O, hiddenKeys); }; },{"./_enum-bug-keys":32,"./_object-keys-internal":77}],75:[function(require,module,exports){ exports.f = Object.getOwnPropertySymbols; },{}],76:[function(require,module,exports){ // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = require('./_has') , toObject = require('./_to-object') , IE_PROTO = require('./_shared-key')('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; },{"./_has":41,"./_shared-key":95,"./_to-object":111}],77:[function(require,module,exports){ var has = require('./_has') , toIObject = require('./_to-iobject') , arrayIndexOf = require('./_array-includes')(false) , IE_PROTO = require('./_shared-key')('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; },{"./_array-includes":13,"./_has":41,"./_shared-key":95,"./_to-iobject":109}],78:[function(require,module,exports){ // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = require('./_object-keys-internal') , enumBugKeys = require('./_enum-bug-keys'); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; },{"./_enum-bug-keys":32,"./_object-keys-internal":77}],79:[function(require,module,exports){ exports.f = {}.propertyIsEnumerable; },{}],80:[function(require,module,exports){ // most Object methods by ES6 should accept primitives var $export = require('./_export') , core = require('./_core') , fails = require('./_fails'); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; },{"./_core":25,"./_export":34,"./_fails":36}],81:[function(require,module,exports){ var getKeys = require('./_object-keys') , toIObject = require('./_to-iobject') , isEnum = require('./_object-pie').f; module.exports = function(isEntries){ return function(it){ var O = toIObject(it) , keys = getKeys(O) , length = keys.length , i = 0 , result = [] , key; while(length > i)if(isEnum.call(O, key = keys[i++])){ result.push(isEntries ? [key, O[key]] : O[key]); } return result; }; }; },{"./_object-keys":78,"./_object-pie":79,"./_to-iobject":109}],82:[function(require,module,exports){ // all object keys, includes non-enumerable and symbols var gOPN = require('./_object-gopn') , gOPS = require('./_object-gops') , anObject = require('./_an-object') , Reflect = require('./_global').Reflect; module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){ var keys = gOPN.f(anObject(it)) , getSymbols = gOPS.f; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; },{"./_an-object":9,"./_global":40,"./_object-gopn":74,"./_object-gops":75}],83:[function(require,module,exports){ var $parseFloat = require('./_global').parseFloat , $trim = require('./_string-trim').trim; module.exports = 1 / $parseFloat(require('./_string-ws') + '-0') !== -Infinity ? function parseFloat(str){ var string = $trim(String(str), 3) , result = $parseFloat(string); return result === 0 && string.charAt(0) == '-' ? -0 : result; } : $parseFloat; },{"./_global":40,"./_string-trim":104,"./_string-ws":105}],84:[function(require,module,exports){ var $parseInt = require('./_global').parseInt , $trim = require('./_string-trim').trim , ws = require('./_string-ws') , hex = /^[\-+]?0[xX]/; module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){ var string = $trim(String(str), 3); return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); } : $parseInt; },{"./_global":40,"./_string-trim":104,"./_string-ws":105}],85:[function(require,module,exports){ 'use strict'; var path = require('./_path') , invoke = require('./_invoke') , aFunction = require('./_a-function'); module.exports = function(/* ...pargs */){ var fn = aFunction(this) , length = arguments.length , pargs = Array(length) , i = 0 , _ = path._ , holder = false; while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; return function(/* ...args */){ var that = this , aLen = arguments.length , j = 0, k = 0, args; if(!holder && !aLen)return invoke(fn, pargs, that); args = pargs.slice(); if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++]; while(aLen > k)args.push(arguments[k++]); return invoke(fn, args, that); }; }; },{"./_a-function":5,"./_invoke":46,"./_path":86}],86:[function(require,module,exports){ module.exports = require('./_global'); },{"./_global":40}],87:[function(require,module,exports){ module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; },{}],88:[function(require,module,exports){ var redefine = require('./_redefine'); module.exports = function(target, src, safe){ for(var key in src)redefine(target, key, src[key], safe); return target; }; },{"./_redefine":89}],89:[function(require,module,exports){ var global = require('./_global') , hide = require('./_hide') , has = require('./_has') , SRC = require('./_uid')('src') , TO_STRING = 'toString' , $toString = Function[TO_STRING] , TPL = ('' + $toString).split(TO_STRING); require('./_core').inspectSource = function(it){ return $toString.call(it); }; (module.exports = function(O, key, val, safe){ var isFunction = typeof val == 'function'; if(isFunction)has(val, 'name') || hide(val, 'name', key); if(O[key] === val)return; if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); if(O === global){ O[key] = val; } else { if(!safe){ delete O[key]; hide(O, key, val); } else { if(O[key])O[key] = val; else hide(O, key, val); } } // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, TO_STRING, function toString(){ return typeof this == 'function' && this[SRC] || $toString.call(this); }); },{"./_core":25,"./_global":40,"./_has":41,"./_hide":42,"./_uid":116}],90:[function(require,module,exports){ module.exports = function(regExp, replace){ var replacer = replace === Object(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(it).replace(regExp, replacer); }; }; },{}],91:[function(require,module,exports){ // 7.2.9 SameValue(x, y) module.exports = Object.is || function is(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; },{}],92:[function(require,module,exports){ // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = require('./_is-object') , anObject = require('./_an-object'); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function(test, buggy, set){ try { set = require('./_ctx')(Function.call, require('./_object-gopd').f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; },{"./_an-object":9,"./_ctx":27,"./_is-object":51,"./_object-gopd":72}],93:[function(require,module,exports){ 'use strict'; var global = require('./_global') , dP = require('./_object-dp') , DESCRIPTORS = require('./_descriptors') , SPECIES = require('./_wks')('species'); module.exports = function(KEY){ var C = global[KEY]; if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, { configurable: true, get: function(){ return this; } }); }; },{"./_descriptors":30,"./_global":40,"./_object-dp":69,"./_wks":119}],94:[function(require,module,exports){ var def = require('./_object-dp').f , has = require('./_has') , TAG = require('./_wks')('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; },{"./_has":41,"./_object-dp":69,"./_wks":119}],95:[function(require,module,exports){ var shared = require('./_shared')('keys') , uid = require('./_uid'); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; },{"./_shared":96,"./_uid":116}],96:[function(require,module,exports){ var global = require('./_global') , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; },{"./_global":40}],97:[function(require,module,exports){ // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = require('./_an-object') , aFunction = require('./_a-function') , SPECIES = require('./_wks')('species'); module.exports = function(O, D){ var C = anObject(O).constructor, S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; },{"./_a-function":5,"./_an-object":9,"./_wks":119}],98:[function(require,module,exports){ var fails = require('./_fails'); module.exports = function(method, arg){ return !!method && fails(function(){ arg ? method.call(null, function(){}, 1) : method.call(null); }); }; },{"./_fails":36}],99:[function(require,module,exports){ var toInteger = require('./_to-integer') , defined = require('./_defined'); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; },{"./_defined":29,"./_to-integer":108}],100:[function(require,module,exports){ // helper for String#{startsWith, endsWith, includes} var isRegExp = require('./_is-regexp') , defined = require('./_defined'); module.exports = function(that, searchString, NAME){ if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!"); return String(defined(that)); }; },{"./_defined":29,"./_is-regexp":52}],101:[function(require,module,exports){ var $export = require('./_export') , fails = require('./_fails') , defined = require('./_defined') , quot = /"/g; // B.2.3.2.1 CreateHTML(string, tag, attribute, value) var createHTML = function(string, tag, attribute, value) { var S = String(defined(string)) , p1 = '<' + tag; if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '&quot;') + '"'; return p1 + '>' + S + '</' + tag + '>'; }; module.exports = function(NAME, exec){ var O = {}; O[NAME] = exec(createHTML); $export($export.P + $export.F * fails(function(){ var test = ''[NAME]('"'); return test !== test.toLowerCase() || test.split('"').length > 3; }), 'String', O); }; },{"./_defined":29,"./_export":34,"./_fails":36}],102:[function(require,module,exports){ // https://github.com/tc39/proposal-string-pad-start-end var toLength = require('./_to-length') , repeat = require('./_string-repeat') , defined = require('./_defined'); module.exports = function(that, maxLength, fillString, left){ var S = String(defined(that)) , stringLength = S.length , fillStr = fillString === undefined ? ' ' : String(fillString) , intMaxLength = toLength(maxLength); if(intMaxLength <= stringLength || fillStr == '')return S; var fillLen = intMaxLength - stringLength , stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen); return left ? stringFiller + S : S + stringFiller; }; },{"./_defined":29,"./_string-repeat":103,"./_to-length":110}],103:[function(require,module,exports){ 'use strict'; var toInteger = require('./_to-integer') , defined = require('./_defined'); module.exports = function repeat(count){ var str = String(defined(this)) , res = '' , n = toInteger(count); if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; }; },{"./_defined":29,"./_to-integer":108}],104:[function(require,module,exports){ var $export = require('./_export') , defined = require('./_defined') , fails = require('./_fails') , spaces = require('./_string-ws') , space = '[' + spaces + ']' , non = '\u200b\u0085' , ltrim = RegExp('^' + space + space + '*') , rtrim = RegExp(space + space + '*$'); var exporter = function(KEY, exec, ALIAS){ var exp = {}; var FORCE = fails(function(){ return !!spaces[KEY]() || non[KEY]() != non; }); var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; if(ALIAS)exp[ALIAS] = fn; $export($export.P + $export.F * FORCE, 'String', exp); }; // 1 -> String#trimLeft // 2 -> String#trimRight // 3 -> String#trim var trim = exporter.trim = function(string, TYPE){ string = String(defined(string)); if(TYPE & 1)string = string.replace(ltrim, ''); if(TYPE & 2)string = string.replace(rtrim, ''); return string; }; module.exports = exporter; },{"./_defined":29,"./_export":34,"./_fails":36,"./_string-ws":105}],105:[function(require,module,exports){ module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; },{}],106:[function(require,module,exports){ var ctx = require('./_ctx') , invoke = require('./_invoke') , html = require('./_html') , cel = require('./_dom-create') , global = require('./_global') , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; var run = function(){ var id = +this; if(queue.hasOwnProperty(id)){ var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function(event){ run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!setTask || !clearTask){ setTask = function setImmediate(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id){ delete queue[id]; }; // Node.js 0.8- if(require('./_cof')(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if(MessageChannel){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ defer = function(id){ global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); // IE8- } else if(ONREADYSTATECHANGE in cel('script')){ defer = function(id){ html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; },{"./_cof":20,"./_ctx":27,"./_dom-create":31,"./_global":40,"./_html":43,"./_invoke":46}],107:[function(require,module,exports){ var toInteger = require('./_to-integer') , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; },{"./_to-integer":108}],108:[function(require,module,exports){ // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; },{}],109:[function(require,module,exports){ // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = require('./_iobject') , defined = require('./_defined'); module.exports = function(it){ return IObject(defined(it)); }; },{"./_defined":29,"./_iobject":47}],110:[function(require,module,exports){ // 7.1.15 ToLength var toInteger = require('./_to-integer') , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; },{"./_to-integer":108}],111:[function(require,module,exports){ // 7.1.13 ToObject(argument) var defined = require('./_defined'); module.exports = function(it){ return Object(defined(it)); }; },{"./_defined":29}],112:[function(require,module,exports){ // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = require('./_is-object'); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; },{"./_is-object":51}],113:[function(require,module,exports){ 'use strict'; if(require('./_descriptors')){ var LIBRARY = require('./_library') , global = require('./_global') , fails = require('./_fails') , $export = require('./_export') , $typed = require('./_typed') , $buffer = require('./_typed-buffer') , ctx = require('./_ctx') , anInstance = require('./_an-instance') , propertyDesc = require('./_property-desc') , hide = require('./_hide') , redefineAll = require('./_redefine-all') , toInteger = require('./_to-integer') , toLength = require('./_to-length') , toIndex = require('./_to-index') , toPrimitive = require('./_to-primitive') , has = require('./_has') , same = require('./_same-value') , classof = require('./_classof') , isObject = require('./_is-object') , toObject = require('./_to-object') , isArrayIter = require('./_is-array-iter') , create = require('./_object-create') , getPrototypeOf = require('./_object-gpo') , gOPN = require('./_object-gopn').f , getIterFn = require('./core.get-iterator-method') , uid = require('./_uid') , wks = require('./_wks') , createArrayMethod = require('./_array-methods') , createArrayIncludes = require('./_array-includes') , speciesConstructor = require('./_species-constructor') , ArrayIterators = require('./es6.array.iterator') , Iterators = require('./_iterators') , $iterDetect = require('./_iter-detect') , setSpecies = require('./_set-species') , arrayFill = require('./_array-fill') , arrayCopyWithin = require('./_array-copy-within') , $DP = require('./_object-dp') , $GOPD = require('./_object-gopd') , dP = $DP.f , gOPD = $GOPD.f , RangeError = global.RangeError , TypeError = global.TypeError , Uint8Array = global.Uint8Array , ARRAY_BUFFER = 'ArrayBuffer' , SHARED_BUFFER = 'Shared' + ARRAY_BUFFER , BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT' , PROTOTYPE = 'prototype' , ArrayProto = Array[PROTOTYPE] , $ArrayBuffer = $buffer.ArrayBuffer , $DataView = $buffer.DataView , arrayForEach = createArrayMethod(0) , arrayFilter = createArrayMethod(2) , arraySome = createArrayMethod(3) , arrayEvery = createArrayMethod(4) , arrayFind = createArrayMethod(5) , arrayFindIndex = createArrayMethod(6) , arrayIncludes = createArrayIncludes(true) , arrayIndexOf = createArrayIncludes(false) , arrayValues = ArrayIterators.values , arrayKeys = ArrayIterators.keys , arrayEntries = ArrayIterators.entries , arrayLastIndexOf = ArrayProto.lastIndexOf , arrayReduce = ArrayProto.reduce , arrayReduceRight = ArrayProto.reduceRight , arrayJoin = ArrayProto.join , arraySort = ArrayProto.sort , arraySlice = ArrayProto.slice , arrayToString = ArrayProto.toString , arrayToLocaleString = ArrayProto.toLocaleString , ITERATOR = wks('iterator') , TAG = wks('toStringTag') , TYPED_CONSTRUCTOR = uid('typed_constructor') , DEF_CONSTRUCTOR = uid('def_constructor') , ALL_CONSTRUCTORS = $typed.CONSTR , TYPED_ARRAY = $typed.TYPED , VIEW = $typed.VIEW , WRONG_LENGTH = 'Wrong length!'; var $map = createArrayMethod(1, function(O, length){ return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); }); var LITTLE_ENDIAN = fails(function(){ return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; }); var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){ new Uint8Array(1).set({}); }); var strictToLength = function(it, SAME){ if(it === undefined)throw TypeError(WRONG_LENGTH); var number = +it , length = toLength(it); if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH); return length; }; var toOffset = function(it, BYTES){ var offset = toInteger(it); if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!'); return offset; }; var validate = function(it){ if(isObject(it) && TYPED_ARRAY in it)return it; throw TypeError(it + ' is not a typed array!'); }; var allocate = function(C, length){ if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){ throw TypeError('It is not a typed array constructor!'); } return new C(length); }; var speciesFromList = function(O, list){ return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); }; var fromList = function(C, list){ var index = 0 , length = list.length , result = allocate(C, length); while(length > index)result[index] = list[index++]; return result; }; var addGetter = function(it, key, internal){ dP(it, key, {get: function(){ return this._d[internal]; }}); }; var $from = function from(source /*, mapfn, thisArg */){ var O = toObject(source) , aLen = arguments.length , mapfn = aLen > 1 ? arguments[1] : undefined , mapping = mapfn !== undefined , iterFn = getIterFn(O) , i, length, values, result, step, iterator; if(iterFn != undefined && !isArrayIter(iterFn)){ for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){ values.push(step.value); } O = values; } if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2); for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){ result[i] = mapping ? mapfn(O[i], i) : O[i]; } return result; }; var $of = function of(/*...items*/){ var index = 0 , length = arguments.length , result = allocate(this, length); while(length > index)result[index] = arguments[index++]; return result; }; // iOS Safari 6.x fails here var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); }); var $toLocaleString = function toLocaleString(){ return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); }; var proto = { copyWithin: function copyWithin(target, start /*, end */){ return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); }, every: function every(callbackfn /*, thisArg */){ return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }, fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars return arrayFill.apply(validate(this), arguments); }, filter: function filter(callbackfn /*, thisArg */){ return speciesFromList(this, arrayFilter(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined)); }, find: function find(predicate /*, thisArg */){ return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }, findIndex: function findIndex(predicate /*, thisArg */){ return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }, forEach: function forEach(callbackfn /*, thisArg */){ arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }, indexOf: function indexOf(searchElement /*, fromIndex */){ return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }, includes: function includes(searchElement /*, fromIndex */){ return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }, join: function join(separator){ // eslint-disable-line no-unused-vars return arrayJoin.apply(validate(this), arguments); }, lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars return arrayLastIndexOf.apply(validate(this), arguments); }, map: function map(mapfn /*, thisArg */){ return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); }, reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars return arrayReduce.apply(validate(this), arguments); }, reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars return arrayReduceRight.apply(validate(this), arguments); }, reverse: function reverse(){ var that = this , length = validate(that).length , middle = Math.floor(length / 2) , index = 0 , value; while(index < middle){ value = that[index]; that[index++] = that[--length]; that[length] = value; } return that; }, some: function some(callbackfn /*, thisArg */){ return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }, sort: function sort(comparefn){ return arraySort.call(validate(this), comparefn); }, subarray: function subarray(begin, end){ var O = validate(this) , length = O.length , $begin = toIndex(begin, length); return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( O.buffer, O.byteOffset + $begin * O.BYTES_PER_ELEMENT, toLength((end === undefined ? length : toIndex(end, length)) - $begin) ); } }; var $slice = function slice(start, end){ return speciesFromList(this, arraySlice.call(validate(this), start, end)); }; var $set = function set(arrayLike /*, offset */){ validate(this); var offset = toOffset(arguments[1], 1) , length = this.length , src = toObject(arrayLike) , len = toLength(src.length) , index = 0; if(len + offset > length)throw RangeError(WRONG_LENGTH); while(index < len)this[offset + index] = src[index++]; }; var $iterators = { entries: function entries(){ return arrayEntries.call(validate(this)); }, keys: function keys(){ return arrayKeys.call(validate(this)); }, values: function values(){ return arrayValues.call(validate(this)); } }; var isTAIndex = function(target, key){ return isObject(target) && target[TYPED_ARRAY] && typeof key != 'symbol' && key in target && String(+key) == String(key); }; var $getDesc = function getOwnPropertyDescriptor(target, key){ return isTAIndex(target, key = toPrimitive(key, true)) ? propertyDesc(2, target[key]) : gOPD(target, key); }; var $setDesc = function defineProperty(target, key, desc){ if(isTAIndex(target, key = toPrimitive(key, true)) && isObject(desc) && has(desc, 'value') && !has(desc, 'get') && !has(desc, 'set') // TODO: add validation descriptor w/o calling accessors && !desc.configurable && (!has(desc, 'writable') || desc.writable) && (!has(desc, 'enumerable') || desc.enumerable) ){ target[key] = desc.value; return target; } else return dP(target, key, desc); }; if(!ALL_CONSTRUCTORS){ $GOPD.f = $getDesc; $DP.f = $setDesc; } $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { getOwnPropertyDescriptor: $getDesc, defineProperty: $setDesc }); if(fails(function(){ arrayToString.call({}); })){ arrayToString = arrayToLocaleString = function toString(){ return arrayJoin.call(this); } } var $TypedArrayPrototype$ = redefineAll({}, proto); redefineAll($TypedArrayPrototype$, $iterators); hide($TypedArrayPrototype$, ITERATOR, $iterators.values); redefineAll($TypedArrayPrototype$, { slice: $slice, set: $set, constructor: function(){ /* noop */ }, toString: arrayToString, toLocaleString: $toLocaleString }); addGetter($TypedArrayPrototype$, 'buffer', 'b'); addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); addGetter($TypedArrayPrototype$, 'byteLength', 'l'); addGetter($TypedArrayPrototype$, 'length', 'e'); dP($TypedArrayPrototype$, TAG, { get: function(){ return this[TYPED_ARRAY]; } }); module.exports = function(KEY, BYTES, wrapper, CLAMPED){ CLAMPED = !!CLAMPED; var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array' , ISNT_UINT8 = NAME != 'Uint8Array' , GETTER = 'get' + KEY , SETTER = 'set' + KEY , TypedArray = global[NAME] , Base = TypedArray || {} , TAC = TypedArray && getPrototypeOf(TypedArray) , FORCED = !TypedArray || !$typed.ABV , O = {} , TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; var getter = function(that, index){ var data = that._d; return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); }; var setter = function(that, index, value){ var data = that._d; if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); }; var addElement = function(that, index){ dP(that, index, { get: function(){ return getter(this, index); }, set: function(value){ return setter(this, index, value); }, enumerable: true }); }; if(FORCED){ TypedArray = wrapper(function(that, data, $offset, $length){ anInstance(that, TypedArray, NAME, '_d'); var index = 0 , offset = 0 , buffer, byteLength, length, klass; if(!isObject(data)){ length = strictToLength(data, true) byteLength = length * BYTES; buffer = new $ArrayBuffer(byteLength); } else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ buffer = data; offset = toOffset($offset, BYTES); var $len = data.byteLength; if($length === undefined){ if($len % BYTES)throw RangeError(WRONG_LENGTH); byteLength = $len - offset; if(byteLength < 0)throw RangeError(WRONG_LENGTH); } else { byteLength = toLength($length) * BYTES; if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH); } length = byteLength / BYTES; } else if(TYPED_ARRAY in data){ return fromList(TypedArray, data); } else { return $from.call(TypedArray, data); } hide(that, '_d', { b: buffer, o: offset, l: byteLength, e: length, v: new $DataView(buffer) }); while(index < length)addElement(that, index++); }); TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); hide(TypedArrayPrototype, 'constructor', TypedArray); } else if(!$iterDetect(function(iter){ // V8 works with iterators, but fails in many other cases // https://code.google.com/p/v8/issues/detail?id=4552 new TypedArray(null); // eslint-disable-line no-new new TypedArray(iter); // eslint-disable-line no-new }, true)){ TypedArray = wrapper(function(that, data, $offset, $length){ anInstance(that, TypedArray, NAME); var klass; // `ws` module bug, temporarily remove validation length for Uint8Array // https://github.com/websockets/ws/pull/645 if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8)); if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ return $length !== undefined ? new Base(data, toOffset($offset, BYTES), $length) : $offset !== undefined ? new Base(data, toOffset($offset, BYTES)) : new Base(data); } if(TYPED_ARRAY in data)return fromList(TypedArray, data); return $from.call(TypedArray, data); }); arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){ if(!(key in TypedArray))hide(TypedArray, key, Base[key]); }); TypedArray[PROTOTYPE] = TypedArrayPrototype; if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray; } var $nativeIterator = TypedArrayPrototype[ITERATOR] , CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined) , $iterator = $iterators.values; hide(TypedArray, TYPED_CONSTRUCTOR, true); hide(TypedArrayPrototype, TYPED_ARRAY, NAME); hide(TypedArrayPrototype, VIEW, true); hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){ dP(TypedArrayPrototype, TAG, { get: function(){ return NAME; } }); } O[NAME] = TypedArray; $export($export.G + $export.W + $export.F * (TypedArray != Base), O); $export($export.S, NAME, { BYTES_PER_ELEMENT: BYTES, from: $from, of: $of }); if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); $export($export.P, NAME, proto); setSpecies(NAME); $export($export.P + $export.F * FORCED_SET, NAME, {set: $set}); $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); $export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString}); $export($export.P + $export.F * fails(function(){ new TypedArray(1).slice(); }), NAME, {slice: $slice}); $export($export.P + $export.F * (fails(function(){ return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString() }) || !fails(function(){ TypedArrayPrototype.toLocaleString.call([1, 2]); })), NAME, {toLocaleString: $toLocaleString}); Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator); }; } else module.exports = function(){ /* empty */ }; },{"./_an-instance":8,"./_array-copy-within":10,"./_array-fill":11,"./_array-includes":13,"./_array-methods":14,"./_classof":19,"./_ctx":27,"./_descriptors":30,"./_export":34,"./_fails":36,"./_global":40,"./_has":41,"./_hide":42,"./_is-array-iter":48,"./_is-object":51,"./_iter-detect":56,"./_iterators":58,"./_library":60,"./_object-create":68,"./_object-dp":69,"./_object-gopd":72,"./_object-gopn":74,"./_object-gpo":76,"./_property-desc":87,"./_redefine-all":88,"./_same-value":91,"./_set-species":93,"./_species-constructor":97,"./_to-index":107,"./_to-integer":108,"./_to-length":110,"./_to-object":111,"./_to-primitive":112,"./_typed":115,"./_typed-buffer":114,"./_uid":116,"./_wks":119,"./core.get-iterator-method":120,"./es6.array.iterator":132}],114:[function(require,module,exports){ 'use strict'; var global = require('./_global') , DESCRIPTORS = require('./_descriptors') , LIBRARY = require('./_library') , $typed = require('./_typed') , hide = require('./_hide') , redefineAll = require('./_redefine-all') , fails = require('./_fails') , anInstance = require('./_an-instance') , toInteger = require('./_to-integer') , toLength = require('./_to-length') , gOPN = require('./_object-gopn').f , dP = require('./_object-dp').f , arrayFill = require('./_array-fill') , setToStringTag = require('./_set-to-string-tag') , ARRAY_BUFFER = 'ArrayBuffer' , DATA_VIEW = 'DataView' , PROTOTYPE = 'prototype' , WRONG_LENGTH = 'Wrong length!' , WRONG_INDEX = 'Wrong index!' , $ArrayBuffer = global[ARRAY_BUFFER] , $DataView = global[DATA_VIEW] , Math = global.Math , RangeError = global.RangeError , Infinity = global.Infinity , BaseBuffer = $ArrayBuffer , abs = Math.abs , pow = Math.pow , floor = Math.floor , log = Math.log , LN2 = Math.LN2 , BUFFER = 'buffer' , BYTE_LENGTH = 'byteLength' , BYTE_OFFSET = 'byteOffset' , $BUFFER = DESCRIPTORS ? '_b' : BUFFER , $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH , $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; // IEEE754 conversions based on https://github.com/feross/ieee754 var packIEEE754 = function(value, mLen, nBytes){ var buffer = Array(nBytes) , eLen = nBytes * 8 - mLen - 1 , eMax = (1 << eLen) - 1 , eBias = eMax >> 1 , rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0 , i = 0 , s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0 , e, m, c; value = abs(value) if(value != value || value === Infinity){ m = value != value ? 1 : 0; e = eMax; } else { e = floor(log(value) / LN2); if(value * (c = pow(2, -e)) < 1){ e--; c *= 2; } if(e + eBias >= 1){ value += rt / c; } else { value += rt * pow(2, 1 - eBias); } if(value * c >= 2){ e++; c /= 2; } if(e + eBias >= eMax){ m = 0; e = eMax; } else if(e + eBias >= 1){ m = (value * c - 1) * pow(2, mLen); e = e + eBias; } else { m = value * pow(2, eBias - 1) * pow(2, mLen); e = 0; } } for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); e = e << mLen | m; eLen += mLen; for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); buffer[--i] |= s * 128; return buffer; }; var unpackIEEE754 = function(buffer, mLen, nBytes){ var eLen = nBytes * 8 - mLen - 1 , eMax = (1 << eLen) - 1 , eBias = eMax >> 1 , nBits = eLen - 7 , i = nBytes - 1 , s = buffer[i--] , e = s & 127 , m; s >>= 7; for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); m = e & (1 << -nBits) - 1; e >>= -nBits; nBits += mLen; for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); if(e === 0){ e = 1 - eBias; } else if(e === eMax){ return m ? NaN : s ? -Infinity : Infinity; } else { m = m + pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * pow(2, e - mLen); }; var unpackI32 = function(bytes){ return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; }; var packI8 = function(it){ return [it & 0xff]; }; var packI16 = function(it){ return [it & 0xff, it >> 8 & 0xff]; }; var packI32 = function(it){ return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; }; var packF64 = function(it){ return packIEEE754(it, 52, 8); }; var packF32 = function(it){ return packIEEE754(it, 23, 4); }; var addGetter = function(C, key, internal){ dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }}); }; var get = function(view, bytes, index, isLittleEndian){ var numIndex = +index , intIndex = toInteger(numIndex); if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX); var store = view[$BUFFER]._b , start = intIndex + view[$OFFSET] , pack = store.slice(start, start + bytes); return isLittleEndian ? pack : pack.reverse(); }; var set = function(view, bytes, index, conversion, value, isLittleEndian){ var numIndex = +index , intIndex = toInteger(numIndex); if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX); var store = view[$BUFFER]._b , start = intIndex + view[$OFFSET] , pack = conversion(+value); for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; }; var validateArrayBufferArguments = function(that, length){ anInstance(that, $ArrayBuffer, ARRAY_BUFFER); var numberLength = +length , byteLength = toLength(numberLength); if(numberLength != byteLength)throw RangeError(WRONG_LENGTH); return byteLength; }; if(!$typed.ABV){ $ArrayBuffer = function ArrayBuffer(length){ var byteLength = validateArrayBufferArguments(this, length); this._b = arrayFill.call(Array(byteLength), 0); this[$LENGTH] = byteLength; }; $DataView = function DataView(buffer, byteOffset, byteLength){ anInstance(this, $DataView, DATA_VIEW); anInstance(buffer, $ArrayBuffer, DATA_VIEW); var bufferLength = buffer[$LENGTH] , offset = toInteger(byteOffset); if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!'); byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH); this[$BUFFER] = buffer; this[$OFFSET] = offset; this[$LENGTH] = byteLength; }; if(DESCRIPTORS){ addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); addGetter($DataView, BUFFER, '_b'); addGetter($DataView, BYTE_LENGTH, '_l'); addGetter($DataView, BYTE_OFFSET, '_o'); } redefineAll($DataView[PROTOTYPE], { getInt8: function getInt8(byteOffset){ return get(this, 1, byteOffset)[0] << 24 >> 24; }, getUint8: function getUint8(byteOffset){ return get(this, 1, byteOffset)[0]; }, getInt16: function getInt16(byteOffset /*, littleEndian */){ var bytes = get(this, 2, byteOffset, arguments[1]); return (bytes[1] << 8 | bytes[0]) << 16 >> 16; }, getUint16: function getUint16(byteOffset /*, littleEndian */){ var bytes = get(this, 2, byteOffset, arguments[1]); return bytes[1] << 8 | bytes[0]; }, getInt32: function getInt32(byteOffset /*, littleEndian */){ return unpackI32(get(this, 4, byteOffset, arguments[1])); }, getUint32: function getUint32(byteOffset /*, littleEndian */){ return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; }, getFloat32: function getFloat32(byteOffset /*, littleEndian */){ return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); }, getFloat64: function getFloat64(byteOffset /*, littleEndian */){ return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); }, setInt8: function setInt8(byteOffset, value){ set(this, 1, byteOffset, packI8, value); }, setUint8: function setUint8(byteOffset, value){ set(this, 1, byteOffset, packI8, value); }, setInt16: function setInt16(byteOffset, value /*, littleEndian */){ set(this, 2, byteOffset, packI16, value, arguments[2]); }, setUint16: function setUint16(byteOffset, value /*, littleEndian */){ set(this, 2, byteOffset, packI16, value, arguments[2]); }, setInt32: function setInt32(byteOffset, value /*, littleEndian */){ set(this, 4, byteOffset, packI32, value, arguments[2]); }, setUint32: function setUint32(byteOffset, value /*, littleEndian */){ set(this, 4, byteOffset, packI32, value, arguments[2]); }, setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){ set(this, 4, byteOffset, packF32, value, arguments[2]); }, setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){ set(this, 8, byteOffset, packF64, value, arguments[2]); } }); } else { if(!fails(function(){ new $ArrayBuffer; // eslint-disable-line no-new }) || !fails(function(){ new $ArrayBuffer(.5); // eslint-disable-line no-new })){ $ArrayBuffer = function ArrayBuffer(length){ return new BaseBuffer(validateArrayBufferArguments(this, length)); }; var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){ if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]); }; if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer; } // iOS Safari 7.x bug var view = new $DataView(new $ArrayBuffer(2)) , $setInt8 = $DataView[PROTOTYPE].setInt8; view.setInt8(0, 2147483648); view.setInt8(1, 2147483649); if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], { setInt8: function setInt8(byteOffset, value){ $setInt8.call(this, byteOffset, value << 24 >> 24); }, setUint8: function setUint8(byteOffset, value){ $setInt8.call(this, byteOffset, value << 24 >> 24); } }, true); } setToStringTag($ArrayBuffer, ARRAY_BUFFER); setToStringTag($DataView, DATA_VIEW); hide($DataView[PROTOTYPE], $typed.VIEW, true); exports[ARRAY_BUFFER] = $ArrayBuffer; exports[DATA_VIEW] = $DataView; },{"./_an-instance":8,"./_array-fill":11,"./_descriptors":30,"./_fails":36,"./_global":40,"./_hide":42,"./_library":60,"./_object-dp":69,"./_object-gopn":74,"./_redefine-all":88,"./_set-to-string-tag":94,"./_to-integer":108,"./_to-length":110,"./_typed":115}],115:[function(require,module,exports){ var global = require('./_global') , hide = require('./_hide') , uid = require('./_uid') , TYPED = uid('typed_array') , VIEW = uid('view') , ABV = !!(global.ArrayBuffer && global.DataView) , CONSTR = ABV , i = 0, l = 9, Typed; var TypedArrayConstructors = ( 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' ).split(','); while(i < l){ if(Typed = global[TypedArrayConstructors[i++]]){ hide(Typed.prototype, TYPED, true); hide(Typed.prototype, VIEW, true); } else CONSTR = false; } module.exports = { ABV: ABV, CONSTR: CONSTR, TYPED: TYPED, VIEW: VIEW }; },{"./_global":40,"./_hide":42,"./_uid":116}],116:[function(require,module,exports){ var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; },{}],117:[function(require,module,exports){ var global = require('./_global') , core = require('./_core') , LIBRARY = require('./_library') , wksExt = require('./_wks-ext') , defineProperty = require('./_object-dp').f; module.exports = function(name){ var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); }; },{"./_core":25,"./_global":40,"./_library":60,"./_object-dp":69,"./_wks-ext":118}],118:[function(require,module,exports){ exports.f = require('./_wks'); },{"./_wks":119}],119:[function(require,module,exports){ var store = require('./_shared')('wks') , uid = require('./_uid') , Symbol = require('./_global').Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; },{"./_global":40,"./_shared":96,"./_uid":116}],120:[function(require,module,exports){ var classof = require('./_classof') , ITERATOR = require('./_wks')('iterator') , Iterators = require('./_iterators'); module.exports = require('./_core').getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; },{"./_classof":19,"./_core":25,"./_iterators":58,"./_wks":119}],121:[function(require,module,exports){ // https://github.com/benjamingr/RexExp.escape var $export = require('./_export') , $re = require('./_replacer')(/[\\^$*+?.()|[\]{}]/g, '\\$&'); $export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }}); },{"./_export":34,"./_replacer":90}],122:[function(require,module,exports){ // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) var $export = require('./_export'); $export($export.P, 'Array', {copyWithin: require('./_array-copy-within')}); require('./_add-to-unscopables')('copyWithin'); },{"./_add-to-unscopables":7,"./_array-copy-within":10,"./_export":34}],123:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $every = require('./_array-methods')(4); $export($export.P + $export.F * !require('./_strict-method')([].every, true), 'Array', { // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: function every(callbackfn /* , thisArg */){ return $every(this, callbackfn, arguments[1]); } }); },{"./_array-methods":14,"./_export":34,"./_strict-method":98}],124:[function(require,module,exports){ // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) var $export = require('./_export'); $export($export.P, 'Array', {fill: require('./_array-fill')}); require('./_add-to-unscopables')('fill'); },{"./_add-to-unscopables":7,"./_array-fill":11,"./_export":34}],125:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $filter = require('./_array-methods')(2); $export($export.P + $export.F * !require('./_strict-method')([].filter, true), 'Array', { // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: function filter(callbackfn /* , thisArg */){ return $filter(this, callbackfn, arguments[1]); } }); },{"./_array-methods":14,"./_export":34,"./_strict-method":98}],126:[function(require,module,exports){ 'use strict'; // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) var $export = require('./_export') , $find = require('./_array-methods')(6) , KEY = 'findIndex' , forced = true; // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $export($export.P + $export.F * forced, 'Array', { findIndex: function findIndex(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); require('./_add-to-unscopables')(KEY); },{"./_add-to-unscopables":7,"./_array-methods":14,"./_export":34}],127:[function(require,module,exports){ 'use strict'; // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) var $export = require('./_export') , $find = require('./_array-methods')(5) , KEY = 'find' , forced = true; // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $export($export.P + $export.F * forced, 'Array', { find: function find(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); require('./_add-to-unscopables')(KEY); },{"./_add-to-unscopables":7,"./_array-methods":14,"./_export":34}],128:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $forEach = require('./_array-methods')(0) , STRICT = require('./_strict-method')([].forEach, true); $export($export.P + $export.F * !STRICT, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: function forEach(callbackfn /* , thisArg */){ return $forEach(this, callbackfn, arguments[1]); } }); },{"./_array-methods":14,"./_export":34,"./_strict-method":98}],129:[function(require,module,exports){ 'use strict'; var ctx = require('./_ctx') , $export = require('./_export') , toObject = require('./_to-object') , call = require('./_iter-call') , isArrayIter = require('./_is-array-iter') , toLength = require('./_to-length') , createProperty = require('./_create-property') , getIterFn = require('./core.get-iterator-method'); $export($export.S + $export.F * !require('./_iter-detect')(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = toObject(arrayLike) , C = typeof this == 'function' ? this : Array , aLen = arguments.length , mapfn = aLen > 1 ? arguments[1] : undefined , mapping = mapfn !== undefined , index = 0 , iterFn = getIterFn(O) , length, result, step, iterator; if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for(result = new C(length); length > index; index++){ createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } }); },{"./_create-property":26,"./_ctx":27,"./_export":34,"./_is-array-iter":48,"./_iter-call":53,"./_iter-detect":56,"./_to-length":110,"./_to-object":111,"./core.get-iterator-method":120}],130:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $indexOf = require('./_array-includes')(false) , $native = [].indexOf , NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; $export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($native)), 'Array', { // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: function indexOf(searchElement /*, fromIndex = 0 */){ return NEGATIVE_ZERO // convert -0 to +0 ? $native.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments[1]); } }); },{"./_array-includes":13,"./_export":34,"./_strict-method":98}],131:[function(require,module,exports){ // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) var $export = require('./_export'); $export($export.S, 'Array', {isArray: require('./_is-array')}); },{"./_export":34,"./_is-array":49}],132:[function(require,module,exports){ 'use strict'; var addToUnscopables = require('./_add-to-unscopables') , step = require('./_iter-step') , Iterators = require('./_iterators') , toIObject = require('./_to-iobject'); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = require('./_iter-define')(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); },{"./_add-to-unscopables":7,"./_iter-define":55,"./_iter-step":57,"./_iterators":58,"./_to-iobject":109}],133:[function(require,module,exports){ 'use strict'; // 22.1.3.13 Array.prototype.join(separator) var $export = require('./_export') , toIObject = require('./_to-iobject') , arrayJoin = [].join; // fallback for not array-like strings $export($export.P + $export.F * (require('./_iobject') != Object || !require('./_strict-method')(arrayJoin)), 'Array', { join: function join(separator){ return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); } }); },{"./_export":34,"./_iobject":47,"./_strict-method":98,"./_to-iobject":109}],134:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , toIObject = require('./_to-iobject') , toInteger = require('./_to-integer') , toLength = require('./_to-length') , $native = [].lastIndexOf , NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; $export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($native)), 'Array', { // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){ // convert -0 to +0 if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0; var O = toIObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1])); if(index < 0)index = length + index; for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0; return -1; } }); },{"./_export":34,"./_strict-method":98,"./_to-integer":108,"./_to-iobject":109,"./_to-length":110}],135:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $map = require('./_array-methods')(1); $export($export.P + $export.F * !require('./_strict-method')([].map, true), 'Array', { // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: function map(callbackfn /* , thisArg */){ return $map(this, callbackfn, arguments[1]); } }); },{"./_array-methods":14,"./_export":34,"./_strict-method":98}],136:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , createProperty = require('./_create-property'); // WebKit Array.of isn't generic $export($export.S + $export.F * require('./_fails')(function(){ function F(){} return !(Array.of.call(F) instanceof F); }), 'Array', { // 22.1.2.3 Array.of( ...items) of: function of(/* ...args */){ var index = 0 , aLen = arguments.length , result = new (typeof this == 'function' ? this : Array)(aLen); while(aLen > index)createProperty(result, index, arguments[index++]); result.length = aLen; return result; } }); },{"./_create-property":26,"./_export":34,"./_fails":36}],137:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $reduce = require('./_array-reduce'); $export($export.P + $export.F * !require('./_strict-method')([].reduceRight, true), 'Array', { // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: function reduceRight(callbackfn /* , initialValue */){ return $reduce(this, callbackfn, arguments.length, arguments[1], true); } }); },{"./_array-reduce":15,"./_export":34,"./_strict-method":98}],138:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $reduce = require('./_array-reduce'); $export($export.P + $export.F * !require('./_strict-method')([].reduce, true), 'Array', { // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: function reduce(callbackfn /* , initialValue */){ return $reduce(this, callbackfn, arguments.length, arguments[1], false); } }); },{"./_array-reduce":15,"./_export":34,"./_strict-method":98}],139:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , html = require('./_html') , cof = require('./_cof') , toIndex = require('./_to-index') , toLength = require('./_to-length') , arraySlice = [].slice; // fallback for not array-like ES3 strings and DOM objects $export($export.P + $export.F * require('./_fails')(function(){ if(html)arraySlice.call(html); }), 'Array', { slice: function slice(begin, end){ var len = toLength(this.length) , klass = cof(this); end = end === undefined ? len : end; if(klass == 'Array')return arraySlice.call(this, begin, end); var start = toIndex(begin, len) , upTo = toIndex(end, len) , size = toLength(upTo - start) , cloned = Array(size) , i = 0; for(; i < size; i++)cloned[i] = klass == 'String' ? this.charAt(start + i) : this[start + i]; return cloned; } }); },{"./_cof":20,"./_export":34,"./_fails":36,"./_html":43,"./_to-index":107,"./_to-length":110}],140:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $some = require('./_array-methods')(3); $export($export.P + $export.F * !require('./_strict-method')([].some, true), 'Array', { // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: function some(callbackfn /* , thisArg */){ return $some(this, callbackfn, arguments[1]); } }); },{"./_array-methods":14,"./_export":34,"./_strict-method":98}],141:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , aFunction = require('./_a-function') , toObject = require('./_to-object') , fails = require('./_fails') , $sort = [].sort , test = [1, 2, 3]; $export($export.P + $export.F * (fails(function(){ // IE8- test.sort(undefined); }) || !fails(function(){ // V8 bug test.sort(null); // Old WebKit }) || !require('./_strict-method')($sort)), 'Array', { // 22.1.3.25 Array.prototype.sort(comparefn) sort: function sort(comparefn){ return comparefn === undefined ? $sort.call(toObject(this)) : $sort.call(toObject(this), aFunction(comparefn)); } }); },{"./_a-function":5,"./_export":34,"./_fails":36,"./_strict-method":98,"./_to-object":111}],142:[function(require,module,exports){ require('./_set-species')('Array'); },{"./_set-species":93}],143:[function(require,module,exports){ // 20.3.3.1 / 15.9.4.4 Date.now() var $export = require('./_export'); $export($export.S, 'Date', {now: function(){ return new Date().getTime(); }}); },{"./_export":34}],144:[function(require,module,exports){ 'use strict'; // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() var $export = require('./_export') , fails = require('./_fails') , getTime = Date.prototype.getTime; var lz = function(num){ return num > 9 ? num : '0' + num; }; // PhantomJS / old WebKit has a broken implementations $export($export.P + $export.F * (fails(function(){ return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z'; }) || !fails(function(){ new Date(NaN).toISOString(); })), 'Date', { toISOString: function toISOString(){ if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value'); var d = this , y = d.getUTCFullYear() , m = d.getUTCMilliseconds() , s = y < 0 ? '-' : y > 9999 ? '+' : ''; return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; } }); },{"./_export":34,"./_fails":36}],145:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , toObject = require('./_to-object') , toPrimitive = require('./_to-primitive'); $export($export.P + $export.F * require('./_fails')(function(){ return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1; }), 'Date', { toJSON: function toJSON(key){ var O = toObject(this) , pv = toPrimitive(O); return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); } }); },{"./_export":34,"./_fails":36,"./_to-object":111,"./_to-primitive":112}],146:[function(require,module,exports){ var TO_PRIMITIVE = require('./_wks')('toPrimitive') , proto = Date.prototype; if(!(TO_PRIMITIVE in proto))require('./_hide')(proto, TO_PRIMITIVE, require('./_date-to-primitive')); },{"./_date-to-primitive":28,"./_hide":42,"./_wks":119}],147:[function(require,module,exports){ var DateProto = Date.prototype , INVALID_DATE = 'Invalid Date' , TO_STRING = 'toString' , $toString = DateProto[TO_STRING] , getTime = DateProto.getTime; if(new Date(NaN) + '' != INVALID_DATE){ require('./_redefine')(DateProto, TO_STRING, function toString(){ var value = getTime.call(this); return value === value ? $toString.call(this) : INVALID_DATE; }); } },{"./_redefine":89}],148:[function(require,module,exports){ // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) var $export = require('./_export'); $export($export.P, 'Function', {bind: require('./_bind')}); },{"./_bind":18,"./_export":34}],149:[function(require,module,exports){ 'use strict'; var isObject = require('./_is-object') , getPrototypeOf = require('./_object-gpo') , HAS_INSTANCE = require('./_wks')('hasInstance') , FunctionProto = Function.prototype; // 19.2.3.6 Function.prototype[@@hasInstance](V) if(!(HAS_INSTANCE in FunctionProto))require('./_object-dp').f(FunctionProto, HAS_INSTANCE, {value: function(O){ if(typeof this != 'function' || !isObject(O))return false; if(!isObject(this.prototype))return O instanceof this; // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: while(O = getPrototypeOf(O))if(this.prototype === O)return true; return false; }}); },{"./_is-object":51,"./_object-dp":69,"./_object-gpo":76,"./_wks":119}],150:[function(require,module,exports){ var dP = require('./_object-dp').f , createDesc = require('./_property-desc') , has = require('./_has') , FProto = Function.prototype , nameRE = /^\s*function ([^ (]*)/ , NAME = 'name'; var isExtensible = Object.isExtensible || function(){ return true; }; // 19.2.4.2 name NAME in FProto || require('./_descriptors') && dP(FProto, NAME, { configurable: true, get: function(){ try { var that = this , name = ('' + that).match(nameRE)[1]; has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name)); return name; } catch(e){ return ''; } } }); },{"./_descriptors":30,"./_has":41,"./_object-dp":69,"./_property-desc":87}],151:[function(require,module,exports){ 'use strict'; var strong = require('./_collection-strong'); // 23.1 Map Objects module.exports = require('./_collection')('Map', function(get){ return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.1.3.6 Map.prototype.get(key) get: function get(key){ var entry = strong.getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value){ return strong.def(this, key === 0 ? 0 : key, value); } }, strong, true); },{"./_collection":24,"./_collection-strong":21}],152:[function(require,module,exports){ // 20.2.2.3 Math.acosh(x) var $export = require('./_export') , log1p = require('./_math-log1p') , sqrt = Math.sqrt , $acosh = Math.acosh; $export($export.S + $export.F * !($acosh // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 && Math.floor($acosh(Number.MAX_VALUE)) == 710 // Tor Browser bug: Math.acosh(Infinity) -> NaN && $acosh(Infinity) == Infinity ), 'Math', { acosh: function acosh(x){ return (x = +x) < 1 ? NaN : x > 94906265.62425156 ? Math.log(x) + Math.LN2 : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); } }); },{"./_export":34,"./_math-log1p":62}],153:[function(require,module,exports){ // 20.2.2.5 Math.asinh(x) var $export = require('./_export') , $asinh = Math.asinh; function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); } // Tor Browser bug: Math.asinh(0) -> -0 $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh}); },{"./_export":34}],154:[function(require,module,exports){ // 20.2.2.7 Math.atanh(x) var $export = require('./_export') , $atanh = Math.atanh; // Tor Browser bug: Math.atanh(-0) -> 0 $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { atanh: function atanh(x){ return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; } }); },{"./_export":34}],155:[function(require,module,exports){ // 20.2.2.9 Math.cbrt(x) var $export = require('./_export') , sign = require('./_math-sign'); $export($export.S, 'Math', { cbrt: function cbrt(x){ return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); } }); },{"./_export":34,"./_math-sign":63}],156:[function(require,module,exports){ // 20.2.2.11 Math.clz32(x) var $export = require('./_export'); $export($export.S, 'Math', { clz32: function clz32(x){ return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; } }); },{"./_export":34}],157:[function(require,module,exports){ // 20.2.2.12 Math.cosh(x) var $export = require('./_export') , exp = Math.exp; $export($export.S, 'Math', { cosh: function cosh(x){ return (exp(x = +x) + exp(-x)) / 2; } }); },{"./_export":34}],158:[function(require,module,exports){ // 20.2.2.14 Math.expm1(x) var $export = require('./_export') , $expm1 = require('./_math-expm1'); $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1}); },{"./_export":34,"./_math-expm1":61}],159:[function(require,module,exports){ // 20.2.2.16 Math.fround(x) var $export = require('./_export') , sign = require('./_math-sign') , pow = Math.pow , EPSILON = pow(2, -52) , EPSILON32 = pow(2, -23) , MAX32 = pow(2, 127) * (2 - EPSILON32) , MIN32 = pow(2, -126); var roundTiesToEven = function(n){ return n + 1 / EPSILON - 1 / EPSILON; }; $export($export.S, 'Math', { fround: function fround(x){ var $abs = Math.abs(x) , $sign = sign(x) , a, result; if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; a = (1 + EPSILON32 / EPSILON) * $abs; result = a - (a - $abs); if(result > MAX32 || result != result)return $sign * Infinity; return $sign * result; } }); },{"./_export":34,"./_math-sign":63}],160:[function(require,module,exports){ // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) var $export = require('./_export') , abs = Math.abs; $export($export.S, 'Math', { hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , i = 0 , aLen = arguments.length , larg = 0 , arg, div; while(i < aLen){ arg = abs(arguments[i++]); if(larg < arg){ div = larg / arg; sum = sum * div * div + 1; larg = arg; } else if(arg > 0){ div = arg / larg; sum += div * div; } else sum += arg; } return larg === Infinity ? Infinity : larg * Math.sqrt(sum); } }); },{"./_export":34}],161:[function(require,module,exports){ // 20.2.2.18 Math.imul(x, y) var $export = require('./_export') , $imul = Math.imul; // some WebKit versions fails with big numbers, some has wrong arity $export($export.S + $export.F * require('./_fails')(function(){ return $imul(0xffffffff, 5) != -5 || $imul.length != 2; }), 'Math', { imul: function imul(x, y){ var UINT16 = 0xffff , xn = +x , yn = +y , xl = UINT16 & xn , yl = UINT16 & yn; return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); } }); },{"./_export":34,"./_fails":36}],162:[function(require,module,exports){ // 20.2.2.21 Math.log10(x) var $export = require('./_export'); $export($export.S, 'Math', { log10: function log10(x){ return Math.log(x) / Math.LN10; } }); },{"./_export":34}],163:[function(require,module,exports){ // 20.2.2.20 Math.log1p(x) var $export = require('./_export'); $export($export.S, 'Math', {log1p: require('./_math-log1p')}); },{"./_export":34,"./_math-log1p":62}],164:[function(require,module,exports){ // 20.2.2.22 Math.log2(x) var $export = require('./_export'); $export($export.S, 'Math', { log2: function log2(x){ return Math.log(x) / Math.LN2; } }); },{"./_export":34}],165:[function(require,module,exports){ // 20.2.2.28 Math.sign(x) var $export = require('./_export'); $export($export.S, 'Math', {sign: require('./_math-sign')}); },{"./_export":34,"./_math-sign":63}],166:[function(require,module,exports){ // 20.2.2.30 Math.sinh(x) var $export = require('./_export') , expm1 = require('./_math-expm1') , exp = Math.exp; // V8 near Chromium 38 has a problem with very small numbers $export($export.S + $export.F * require('./_fails')(function(){ return !Math.sinh(-2e-17) != -2e-17; }), 'Math', { sinh: function sinh(x){ return Math.abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); } }); },{"./_export":34,"./_fails":36,"./_math-expm1":61}],167:[function(require,module,exports){ // 20.2.2.33 Math.tanh(x) var $export = require('./_export') , expm1 = require('./_math-expm1') , exp = Math.exp; $export($export.S, 'Math', { tanh: function tanh(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); } }); },{"./_export":34,"./_math-expm1":61}],168:[function(require,module,exports){ // 20.2.2.34 Math.trunc(x) var $export = require('./_export'); $export($export.S, 'Math', { trunc: function trunc(it){ return (it > 0 ? Math.floor : Math.ceil)(it); } }); },{"./_export":34}],169:[function(require,module,exports){ 'use strict'; var global = require('./_global') , has = require('./_has') , cof = require('./_cof') , inheritIfRequired = require('./_inherit-if-required') , toPrimitive = require('./_to-primitive') , fails = require('./_fails') , gOPN = require('./_object-gopn').f , gOPD = require('./_object-gopd').f , dP = require('./_object-dp').f , $trim = require('./_string-trim').trim , NUMBER = 'Number' , $Number = global[NUMBER] , Base = $Number , proto = $Number.prototype // Opera ~12 has broken Object#toString , BROKEN_COF = cof(require('./_object-create')(proto)) == NUMBER , TRIM = 'trim' in String.prototype; // 7.1.3 ToNumber(argument) var toNumber = function(argument){ var it = toPrimitive(argument, false); if(typeof it == 'string' && it.length > 2){ it = TRIM ? it.trim() : $trim(it, 3); var first = it.charCodeAt(0) , third, radix, maxCode; if(first === 43 || first === 45){ third = it.charCodeAt(2); if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix } else if(first === 48){ switch(it.charCodeAt(1)){ case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i default : return +it; } for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){ code = digits.charCodeAt(i); // parseInt parses a string to a first unavailable symbol // but ToNumber should return NaN if a string contains unavailable symbols if(code < 48 || code > maxCode)return NaN; } return parseInt(digits, radix); } } return +it; }; if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){ $Number = function Number(value){ var it = arguments.length < 1 ? 0 : value , that = this; return that instanceof $Number // check on 1..constructor(foo) case && (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER) ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); }; for(var keys = require('./_descriptors') ? gOPN(Base) : ( // ES3: 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES6 (in case, if modules with ES6 Number statics required before): 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' ).split(','), j = 0, key; keys.length > j; j++){ if(has(Base, key = keys[j]) && !has($Number, key)){ dP($Number, key, gOPD(Base, key)); } } $Number.prototype = proto; proto.constructor = $Number; require('./_redefine')(global, NUMBER, $Number); } },{"./_cof":20,"./_descriptors":30,"./_fails":36,"./_global":40,"./_has":41,"./_inherit-if-required":45,"./_object-create":68,"./_object-dp":69,"./_object-gopd":72,"./_object-gopn":74,"./_redefine":89,"./_string-trim":104,"./_to-primitive":112}],170:[function(require,module,exports){ // 20.1.2.1 Number.EPSILON var $export = require('./_export'); $export($export.S, 'Number', {EPSILON: Math.pow(2, -52)}); },{"./_export":34}],171:[function(require,module,exports){ // 20.1.2.2 Number.isFinite(number) var $export = require('./_export') , _isFinite = require('./_global').isFinite; $export($export.S, 'Number', { isFinite: function isFinite(it){ return typeof it == 'number' && _isFinite(it); } }); },{"./_export":34,"./_global":40}],172:[function(require,module,exports){ // 20.1.2.3 Number.isInteger(number) var $export = require('./_export'); $export($export.S, 'Number', {isInteger: require('./_is-integer')}); },{"./_export":34,"./_is-integer":50}],173:[function(require,module,exports){ // 20.1.2.4 Number.isNaN(number) var $export = require('./_export'); $export($export.S, 'Number', { isNaN: function isNaN(number){ return number != number; } }); },{"./_export":34}],174:[function(require,module,exports){ // 20.1.2.5 Number.isSafeInteger(number) var $export = require('./_export') , isInteger = require('./_is-integer') , abs = Math.abs; $export($export.S, 'Number', { isSafeInteger: function isSafeInteger(number){ return isInteger(number) && abs(number) <= 0x1fffffffffffff; } }); },{"./_export":34,"./_is-integer":50}],175:[function(require,module,exports){ // 20.1.2.6 Number.MAX_SAFE_INTEGER var $export = require('./_export'); $export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff}); },{"./_export":34}],176:[function(require,module,exports){ // 20.1.2.10 Number.MIN_SAFE_INTEGER var $export = require('./_export'); $export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff}); },{"./_export":34}],177:[function(require,module,exports){ var $export = require('./_export') , $parseFloat = require('./_parse-float'); // 20.1.2.12 Number.parseFloat(string) $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat}); },{"./_export":34,"./_parse-float":83}],178:[function(require,module,exports){ var $export = require('./_export') , $parseInt = require('./_parse-int'); // 20.1.2.13 Number.parseInt(string, radix) $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt}); },{"./_export":34,"./_parse-int":84}],179:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , toInteger = require('./_to-integer') , aNumberValue = require('./_a-number-value') , repeat = require('./_string-repeat') , $toFixed = 1..toFixed , floor = Math.floor , data = [0, 0, 0, 0, 0, 0] , ERROR = 'Number.toFixed: incorrect invocation!' , ZERO = '0'; var multiply = function(n, c){ var i = -1 , c2 = c; while(++i < 6){ c2 += n * data[i]; data[i] = c2 % 1e7; c2 = floor(c2 / 1e7); } }; var divide = function(n){ var i = 6 , c = 0; while(--i >= 0){ c += data[i]; data[i] = floor(c / n); c = (c % n) * 1e7; } }; var numToString = function(){ var i = 6 , s = ''; while(--i >= 0){ if(s !== '' || i === 0 || data[i] !== 0){ var t = String(data[i]); s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; } } return s; }; var pow = function(x, n, acc){ return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); }; var log = function(x){ var n = 0 , x2 = x; while(x2 >= 4096){ n += 12; x2 /= 4096; } while(x2 >= 2){ n += 1; x2 /= 2; } return n; }; $export($export.P + $export.F * (!!$toFixed && ( 0.00008.toFixed(3) !== '0.000' || 0.9.toFixed(0) !== '1' || 1.255.toFixed(2) !== '1.25' || 1000000000000000128..toFixed(0) !== '1000000000000000128' ) || !require('./_fails')(function(){ // V8 ~ Android 4.3- $toFixed.call({}); })), 'Number', { toFixed: function toFixed(fractionDigits){ var x = aNumberValue(this, ERROR) , f = toInteger(fractionDigits) , s = '' , m = ZERO , e, z, j, k; if(f < 0 || f > 20)throw RangeError(ERROR); if(x != x)return 'NaN'; if(x <= -1e21 || x >= 1e21)return String(x); if(x < 0){ s = '-'; x = -x; } if(x > 1e-21){ e = log(x * pow(2, 69, 1)) - 69; z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); z *= 0x10000000000000; e = 52 - e; if(e > 0){ multiply(0, z); j = f; while(j >= 7){ multiply(1e7, 0); j -= 7; } multiply(pow(10, j, 1), 0); j = e - 1; while(j >= 23){ divide(1 << 23); j -= 23; } divide(1 << j); multiply(1, 1); divide(2); m = numToString(); } else { multiply(0, z); multiply(1 << -e, 0); m = numToString() + repeat.call(ZERO, f); } } if(f > 0){ k = m.length; m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); } else { m = s + m; } return m; } }); },{"./_a-number-value":6,"./_export":34,"./_fails":36,"./_string-repeat":103,"./_to-integer":108}],180:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $fails = require('./_fails') , aNumberValue = require('./_a-number-value') , $toPrecision = 1..toPrecision; $export($export.P + $export.F * ($fails(function(){ // IE7- return $toPrecision.call(1, undefined) !== '1'; }) || !$fails(function(){ // V8 ~ Android 4.3- $toPrecision.call({}); })), 'Number', { toPrecision: function toPrecision(precision){ var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); } }); },{"./_a-number-value":6,"./_export":34,"./_fails":36}],181:[function(require,module,exports){ // 19.1.3.1 Object.assign(target, source) var $export = require('./_export'); $export($export.S + $export.F, 'Object', {assign: require('./_object-assign')}); },{"./_export":34,"./_object-assign":67}],182:[function(require,module,exports){ var $export = require('./_export') // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', {create: require('./_object-create')}); },{"./_export":34,"./_object-create":68}],183:[function(require,module,exports){ var $export = require('./_export'); // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) $export($export.S + $export.F * !require('./_descriptors'), 'Object', {defineProperties: require('./_object-dps')}); },{"./_descriptors":30,"./_export":34,"./_object-dps":70}],184:[function(require,module,exports){ var $export = require('./_export'); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !require('./_descriptors'), 'Object', {defineProperty: require('./_object-dp').f}); },{"./_descriptors":30,"./_export":34,"./_object-dp":69}],185:[function(require,module,exports){ // 19.1.2.5 Object.freeze(O) var isObject = require('./_is-object') , meta = require('./_meta').onFreeze; require('./_object-sap')('freeze', function($freeze){ return function freeze(it){ return $freeze && isObject(it) ? $freeze(meta(it)) : it; }; }); },{"./_is-object":51,"./_meta":64,"./_object-sap":80}],186:[function(require,module,exports){ // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = require('./_to-iobject') , $getOwnPropertyDescriptor = require('./_object-gopd').f; require('./_object-sap')('getOwnPropertyDescriptor', function(){ return function getOwnPropertyDescriptor(it, key){ return $getOwnPropertyDescriptor(toIObject(it), key); }; }); },{"./_object-gopd":72,"./_object-sap":80,"./_to-iobject":109}],187:[function(require,module,exports){ // 19.1.2.7 Object.getOwnPropertyNames(O) require('./_object-sap')('getOwnPropertyNames', function(){ return require('./_object-gopn-ext').f; }); },{"./_object-gopn-ext":73,"./_object-sap":80}],188:[function(require,module,exports){ // 19.1.2.9 Object.getPrototypeOf(O) var toObject = require('./_to-object') , $getPrototypeOf = require('./_object-gpo'); require('./_object-sap')('getPrototypeOf', function(){ return function getPrototypeOf(it){ return $getPrototypeOf(toObject(it)); }; }); },{"./_object-gpo":76,"./_object-sap":80,"./_to-object":111}],189:[function(require,module,exports){ // 19.1.2.11 Object.isExtensible(O) var isObject = require('./_is-object'); require('./_object-sap')('isExtensible', function($isExtensible){ return function isExtensible(it){ return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; }; }); },{"./_is-object":51,"./_object-sap":80}],190:[function(require,module,exports){ // 19.1.2.12 Object.isFrozen(O) var isObject = require('./_is-object'); require('./_object-sap')('isFrozen', function($isFrozen){ return function isFrozen(it){ return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; }; }); },{"./_is-object":51,"./_object-sap":80}],191:[function(require,module,exports){ // 19.1.2.13 Object.isSealed(O) var isObject = require('./_is-object'); require('./_object-sap')('isSealed', function($isSealed){ return function isSealed(it){ return isObject(it) ? $isSealed ? $isSealed(it) : false : true; }; }); },{"./_is-object":51,"./_object-sap":80}],192:[function(require,module,exports){ // 19.1.3.10 Object.is(value1, value2) var $export = require('./_export'); $export($export.S, 'Object', {is: require('./_same-value')}); },{"./_export":34,"./_same-value":91}],193:[function(require,module,exports){ // 19.1.2.14 Object.keys(O) var toObject = require('./_to-object') , $keys = require('./_object-keys'); require('./_object-sap')('keys', function(){ return function keys(it){ return $keys(toObject(it)); }; }); },{"./_object-keys":78,"./_object-sap":80,"./_to-object":111}],194:[function(require,module,exports){ // 19.1.2.15 Object.preventExtensions(O) var isObject = require('./_is-object') , meta = require('./_meta').onFreeze; require('./_object-sap')('preventExtensions', function($preventExtensions){ return function preventExtensions(it){ return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; }; }); },{"./_is-object":51,"./_meta":64,"./_object-sap":80}],195:[function(require,module,exports){ // 19.1.2.17 Object.seal(O) var isObject = require('./_is-object') , meta = require('./_meta').onFreeze; require('./_object-sap')('seal', function($seal){ return function seal(it){ return $seal && isObject(it) ? $seal(meta(it)) : it; }; }); },{"./_is-object":51,"./_meta":64,"./_object-sap":80}],196:[function(require,module,exports){ // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = require('./_export'); $export($export.S, 'Object', {setPrototypeOf: require('./_set-proto').set}); },{"./_export":34,"./_set-proto":92}],197:[function(require,module,exports){ 'use strict'; // 19.1.3.6 Object.prototype.toString() var classof = require('./_classof') , test = {}; test[require('./_wks')('toStringTag')] = 'z'; if(test + '' != '[object z]'){ require('./_redefine')(Object.prototype, 'toString', function toString(){ return '[object ' + classof(this) + ']'; }, true); } },{"./_classof":19,"./_redefine":89,"./_wks":119}],198:[function(require,module,exports){ var $export = require('./_export') , $parseFloat = require('./_parse-float'); // 18.2.4 parseFloat(string) $export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat}); },{"./_export":34,"./_parse-float":83}],199:[function(require,module,exports){ var $export = require('./_export') , $parseInt = require('./_parse-int'); // 18.2.5 parseInt(string, radix) $export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt}); },{"./_export":34,"./_parse-int":84}],200:[function(require,module,exports){ 'use strict'; var LIBRARY = require('./_library') , global = require('./_global') , ctx = require('./_ctx') , classof = require('./_classof') , $export = require('./_export') , isObject = require('./_is-object') , aFunction = require('./_a-function') , anInstance = require('./_an-instance') , forOf = require('./_for-of') , speciesConstructor = require('./_species-constructor') , task = require('./_task').set , microtask = require('./_microtask')() , PROMISE = 'Promise' , TypeError = global.TypeError , process = global.process , $Promise = global[PROMISE] , process = global.process , isNode = classof(process) == 'process' , empty = function(){ /* empty */ } , Internal, GenericPromiseCapability, Wrapper; var USE_NATIVE = !!function(){ try { // correct subclassing with @@species support var promise = $Promise.resolve(1) , FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function(exec){ exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch(e){ /* empty */ } }(); // helpers var sameConstructor = function(a, b){ // with library wrapper special case return a === b || a === $Promise && b === Wrapper; }; var isThenable = function(it){ var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var newPromiseCapability = function(C){ return sameConstructor($Promise, C) ? new PromiseCapability(C) : new GenericPromiseCapability(C); }; var PromiseCapability = GenericPromiseCapability = function(C){ var resolve, reject; this.promise = new C(function($$resolve, $$reject){ if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); }; var perform = function(exec){ try { exec(); } catch(e){ return {error: e}; } }; var notify = function(promise, isReject){ if(promise._n)return; promise._n = true; var chain = promise._c; microtask(function(){ var value = promise._v , ok = promise._s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , domain = reaction.domain , result, then; try { if(handler){ if(!ok){ if(promise._h == 2)onHandleUnhandled(promise); promise._h = 1; } if(handler === true)result = value; else { if(domain)domain.enter(); result = handler(value); if(domain)domain.exit(); } if(result === reaction.promise){ reject(TypeError('Promise-chain cycle')); } else if(then = isThenable(result)){ then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch(e){ reject(e); } }; while(chain.length > i)run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if(isReject && !promise._h)onUnhandled(promise); }); }; var onUnhandled = function(promise){ task.call(global, function(){ var value = promise._v , abrupt, handler, console; if(isUnhandled(promise)){ abrupt = perform(function(){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(handler = global.onunhandledrejection){ handler({promise: promise, reason: value}); } else if((console = global.console) && console.error){ console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if(abrupt)throw abrupt.error; }); }; var isUnhandled = function(promise){ if(promise._h == 1)return false; var chain = promise._a || promise._c , i = 0 , reaction; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var onHandleUnhandled = function(promise){ task.call(global, function(){ var handler; if(isNode){ process.emit('rejectionHandled', promise); } else if(handler = global.onrejectionhandled){ handler({promise: promise, reason: promise._v}); } }); }; var $reject = function(value){ var promise = this; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if(!promise._a)promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function(value){ var promise = this , then; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap try { if(promise === value)throw TypeError("Promise can't be resolved itself"); if(then = isThenable(value)){ microtask(function(){ var wrapper = {_w: promise, _d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch(e){ $reject.call({_w: promise, _d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE){ // 25.4.3.1 Promise(executor) $Promise = function Promise(executor){ anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch(err){ $reject.call(this, err); } }; Internal = function Promise(executor){ this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = require('./_redefine-all')($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if(this._a)this._a.push(reaction); if(this._s)notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); PromiseCapability = function(){ var promise = new Internal; this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); require('./_set-to-string-tag')($Promise, PROMISE); require('./_set-species')(PROMISE); Wrapper = require('./_core')[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = newPromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ // instanceof instead of internal slot check because we should fix it without replacement native Promise core if(x instanceof $Promise && sameConstructor(x.constructor, this))return x; var capability = newPromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); $export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function(iter){ $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = this , capability = newPromiseCapability(C) , resolve = capability.resolve , reject = capability.reject; var abrupt = perform(function(){ var values = [] , index = 0 , remaining = 1; forOf(iterable, false, function(promise){ var $index = index++ , alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = this , capability = newPromiseCapability(C) , reject = capability.reject; var abrupt = perform(function(){ forOf(iterable, false, function(promise){ C.resolve(promise).then(capability.resolve, reject); }); }); if(abrupt)reject(abrupt.error); return capability.promise; } }); },{"./_a-function":5,"./_an-instance":8,"./_classof":19,"./_core":25,"./_ctx":27,"./_export":34,"./_for-of":39,"./_global":40,"./_is-object":51,"./_iter-detect":56,"./_library":60,"./_microtask":66,"./_redefine-all":88,"./_set-species":93,"./_set-to-string-tag":94,"./_species-constructor":97,"./_task":106,"./_wks":119}],201:[function(require,module,exports){ // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) var $export = require('./_export') , aFunction = require('./_a-function') , anObject = require('./_an-object') , rApply = (require('./_global').Reflect || {}).apply , fApply = Function.apply; // MS Edge argumentsList argument is optional $export($export.S + $export.F * !require('./_fails')(function(){ rApply(function(){}); }), 'Reflect', { apply: function apply(target, thisArgument, argumentsList){ var T = aFunction(target) , L = anObject(argumentsList); return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); } }); },{"./_a-function":5,"./_an-object":9,"./_export":34,"./_fails":36,"./_global":40}],202:[function(require,module,exports){ // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) var $export = require('./_export') , create = require('./_object-create') , aFunction = require('./_a-function') , anObject = require('./_an-object') , isObject = require('./_is-object') , fails = require('./_fails') , bind = require('./_bind') , rConstruct = (require('./_global').Reflect || {}).construct; // MS Edge supports only 2 arguments and argumentsList argument is optional // FF Nightly sets third argument as `new.target`, but does not create `this` from it var NEW_TARGET_BUG = fails(function(){ function F(){} return !(rConstruct(function(){}, [], F) instanceof F); }); var ARGS_BUG = !fails(function(){ rConstruct(function(){}); }); $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { construct: function construct(Target, args /*, newTarget*/){ aFunction(Target); anObject(args); var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); if(ARGS_BUG && !NEW_TARGET_BUG)return rConstruct(Target, args, newTarget); if(Target == newTarget){ // w/o altered newTarget, optimization for 0-4 arguments switch(args.length){ case 0: return new Target; case 1: return new Target(args[0]); case 2: return new Target(args[0], args[1]); case 3: return new Target(args[0], args[1], args[2]); case 4: return new Target(args[0], args[1], args[2], args[3]); } // w/o altered newTarget, lot of arguments case var $args = [null]; $args.push.apply($args, args); return new (bind.apply(Target, $args)); } // with altered newTarget, not support built-in constructors var proto = newTarget.prototype , instance = create(isObject(proto) ? proto : Object.prototype) , result = Function.apply.call(Target, instance, args); return isObject(result) ? result : instance; } }); },{"./_a-function":5,"./_an-object":9,"./_bind":18,"./_export":34,"./_fails":36,"./_global":40,"./_is-object":51,"./_object-create":68}],203:[function(require,module,exports){ // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) var dP = require('./_object-dp') , $export = require('./_export') , anObject = require('./_an-object') , toPrimitive = require('./_to-primitive'); // MS Edge has broken Reflect.defineProperty - throwing instead of returning false $export($export.S + $export.F * require('./_fails')(function(){ Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2}); }), 'Reflect', { defineProperty: function defineProperty(target, propertyKey, attributes){ anObject(target); propertyKey = toPrimitive(propertyKey, true); anObject(attributes); try { dP.f(target, propertyKey, attributes); return true; } catch(e){ return false; } } }); },{"./_an-object":9,"./_export":34,"./_fails":36,"./_object-dp":69,"./_to-primitive":112}],204:[function(require,module,exports){ // 26.1.4 Reflect.deleteProperty(target, propertyKey) var $export = require('./_export') , gOPD = require('./_object-gopd').f , anObject = require('./_an-object'); $export($export.S, 'Reflect', { deleteProperty: function deleteProperty(target, propertyKey){ var desc = gOPD(anObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; } }); },{"./_an-object":9,"./_export":34,"./_object-gopd":72}],205:[function(require,module,exports){ 'use strict'; // 26.1.5 Reflect.enumerate(target) var $export = require('./_export') , anObject = require('./_an-object'); var Enumerate = function(iterated){ this._t = anObject(iterated); // target this._i = 0; // next index var keys = this._k = [] // keys , key; for(key in iterated)keys.push(key); }; require('./_iter-create')(Enumerate, 'Object', function(){ var that = this , keys = that._k , key; do { if(that._i >= keys.length)return {value: undefined, done: true}; } while(!((key = keys[that._i++]) in that._t)); return {value: key, done: false}; }); $export($export.S, 'Reflect', { enumerate: function enumerate(target){ return new Enumerate(target); } }); },{"./_an-object":9,"./_export":34,"./_iter-create":54}],206:[function(require,module,exports){ // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) var gOPD = require('./_object-gopd') , $export = require('./_export') , anObject = require('./_an-object'); $export($export.S, 'Reflect', { getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ return gOPD.f(anObject(target), propertyKey); } }); },{"./_an-object":9,"./_export":34,"./_object-gopd":72}],207:[function(require,module,exports){ // 26.1.8 Reflect.getPrototypeOf(target) var $export = require('./_export') , getProto = require('./_object-gpo') , anObject = require('./_an-object'); $export($export.S, 'Reflect', { getPrototypeOf: function getPrototypeOf(target){ return getProto(anObject(target)); } }); },{"./_an-object":9,"./_export":34,"./_object-gpo":76}],208:[function(require,module,exports){ // 26.1.6 Reflect.get(target, propertyKey [, receiver]) var gOPD = require('./_object-gopd') , getPrototypeOf = require('./_object-gpo') , has = require('./_has') , $export = require('./_export') , isObject = require('./_is-object') , anObject = require('./_an-object'); function get(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc, proto; if(anObject(target) === receiver)return target[propertyKey]; if(desc = gOPD.f(target, propertyKey))return has(desc, 'value') ? desc.value : desc.get !== undefined ? desc.get.call(receiver) : undefined; if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver); } $export($export.S, 'Reflect', {get: get}); },{"./_an-object":9,"./_export":34,"./_has":41,"./_is-object":51,"./_object-gopd":72,"./_object-gpo":76}],209:[function(require,module,exports){ // 26.1.9 Reflect.has(target, propertyKey) var $export = require('./_export'); $export($export.S, 'Reflect', { has: function has(target, propertyKey){ return propertyKey in target; } }); },{"./_export":34}],210:[function(require,module,exports){ // 26.1.10 Reflect.isExtensible(target) var $export = require('./_export') , anObject = require('./_an-object') , $isExtensible = Object.isExtensible; $export($export.S, 'Reflect', { isExtensible: function isExtensible(target){ anObject(target); return $isExtensible ? $isExtensible(target) : true; } }); },{"./_an-object":9,"./_export":34}],211:[function(require,module,exports){ // 26.1.11 Reflect.ownKeys(target) var $export = require('./_export'); $export($export.S, 'Reflect', {ownKeys: require('./_own-keys')}); },{"./_export":34,"./_own-keys":82}],212:[function(require,module,exports){ // 26.1.12 Reflect.preventExtensions(target) var $export = require('./_export') , anObject = require('./_an-object') , $preventExtensions = Object.preventExtensions; $export($export.S, 'Reflect', { preventExtensions: function preventExtensions(target){ anObject(target); try { if($preventExtensions)$preventExtensions(target); return true; } catch(e){ return false; } } }); },{"./_an-object":9,"./_export":34}],213:[function(require,module,exports){ // 26.1.14 Reflect.setPrototypeOf(target, proto) var $export = require('./_export') , setProto = require('./_set-proto'); if(setProto)$export($export.S, 'Reflect', { setPrototypeOf: function setPrototypeOf(target, proto){ setProto.check(target, proto); try { setProto.set(target, proto); return true; } catch(e){ return false; } } }); },{"./_export":34,"./_set-proto":92}],214:[function(require,module,exports){ // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) var dP = require('./_object-dp') , gOPD = require('./_object-gopd') , getPrototypeOf = require('./_object-gpo') , has = require('./_has') , $export = require('./_export') , createDesc = require('./_property-desc') , anObject = require('./_an-object') , isObject = require('./_is-object'); function set(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = gOPD.f(anObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = getPrototypeOf(target))){ return set(proto, propertyKey, V, receiver); } ownDesc = createDesc(0); } if(has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0); existingDescriptor.value = V; dP.f(receiver, propertyKey, existingDescriptor); return true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } $export($export.S, 'Reflect', {set: set}); },{"./_an-object":9,"./_export":34,"./_has":41,"./_is-object":51,"./_object-dp":69,"./_object-gopd":72,"./_object-gpo":76,"./_property-desc":87}],215:[function(require,module,exports){ var global = require('./_global') , inheritIfRequired = require('./_inherit-if-required') , dP = require('./_object-dp').f , gOPN = require('./_object-gopn').f , isRegExp = require('./_is-regexp') , $flags = require('./_flags') , $RegExp = global.RegExp , Base = $RegExp , proto = $RegExp.prototype , re1 = /a/g , re2 = /a/g // "new" creates a new object, old webkit buggy here , CORRECT_NEW = new $RegExp(re1) !== re1; if(require('./_descriptors') && (!CORRECT_NEW || require('./_fails')(function(){ re2[require('./_wks')('match')] = false; // RegExp constructor can alter flags and IsRegExp works correct with @@match return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; }))){ $RegExp = function RegExp(p, f){ var tiRE = this instanceof $RegExp , piRE = isRegExp(p) , fiU = f === undefined; return !tiRE && piRE && p.constructor === $RegExp && fiU ? p : inheritIfRequired(CORRECT_NEW ? new Base(piRE && !fiU ? p.source : p, f) : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) , tiRE ? this : proto, $RegExp); }; var proxy = function(key){ key in $RegExp || dP($RegExp, key, { configurable: true, get: function(){ return Base[key]; }, set: function(it){ Base[key] = it; } }); }; for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]); proto.constructor = $RegExp; $RegExp.prototype = proto; require('./_redefine')(global, 'RegExp', $RegExp); } require('./_set-species')('RegExp'); },{"./_descriptors":30,"./_fails":36,"./_flags":38,"./_global":40,"./_inherit-if-required":45,"./_is-regexp":52,"./_object-dp":69,"./_object-gopn":74,"./_redefine":89,"./_set-species":93,"./_wks":119}],216:[function(require,module,exports){ // 21.2.5.3 get RegExp.prototype.flags() if(require('./_descriptors') && /./g.flags != 'g')require('./_object-dp').f(RegExp.prototype, 'flags', { configurable: true, get: require('./_flags') }); },{"./_descriptors":30,"./_flags":38,"./_object-dp":69}],217:[function(require,module,exports){ // @@match logic require('./_fix-re-wks')('match', 1, function(defined, MATCH, $match){ // 21.1.3.11 String.prototype.match(regexp) return [function match(regexp){ 'use strict'; var O = defined(this) , fn = regexp == undefined ? undefined : regexp[MATCH]; return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); }, $match]; }); },{"./_fix-re-wks":37}],218:[function(require,module,exports){ // @@replace logic require('./_fix-re-wks')('replace', 2, function(defined, REPLACE, $replace){ // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) return [function replace(searchValue, replaceValue){ 'use strict'; var O = defined(this) , fn = searchValue == undefined ? undefined : searchValue[REPLACE]; return fn !== undefined ? fn.call(searchValue, O, replaceValue) : $replace.call(String(O), searchValue, replaceValue); }, $replace]; }); },{"./_fix-re-wks":37}],219:[function(require,module,exports){ // @@search logic require('./_fix-re-wks')('search', 1, function(defined, SEARCH, $search){ // 21.1.3.15 String.prototype.search(regexp) return [function search(regexp){ 'use strict'; var O = defined(this) , fn = regexp == undefined ? undefined : regexp[SEARCH]; return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); }, $search]; }); },{"./_fix-re-wks":37}],220:[function(require,module,exports){ // @@split logic require('./_fix-re-wks')('split', 2, function(defined, SPLIT, $split){ 'use strict'; var isRegExp = require('./_is-regexp') , _split = $split , $push = [].push , $SPLIT = 'split' , LENGTH = 'length' , LAST_INDEX = 'lastIndex'; if( 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || '.'[$SPLIT](/()()/)[LENGTH] > 1 || ''[$SPLIT](/.?/)[LENGTH] ){ var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group // based on es5-shim implementation, need to rework it $split = function(separator, limit){ var string = String(this); if(separator === undefined && limit === 0)return []; // If `separator` is not a regex, use native split if(!isRegExp(separator))return _split.call(string, separator, limit); var output = []; var flags = (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : '') + (separator.unicode ? 'u' : '') + (separator.sticky ? 'y' : ''); var lastLastIndex = 0; var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; // Make `global` and avoid `lastIndex` issues by working with a copy var separatorCopy = new RegExp(separator.source, flags + 'g'); var separator2, match, lastIndex, lastLength, i; // Doesn't need flags gy, but they don't hurt if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); while(match = separatorCopy.exec(string)){ // `separatorCopy.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0][LENGTH]; if(lastIndex > lastLastIndex){ output.push(string.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){ for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined; }); if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1)); lastLength = match[0][LENGTH]; lastLastIndex = lastIndex; if(output[LENGTH] >= splitLimit)break; } if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop } if(lastLastIndex === string[LENGTH]){ if(lastLength || !separatorCopy.test(''))output.push(''); } else output.push(string.slice(lastLastIndex)); return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; }; // Chakra, V8 } else if('0'[$SPLIT](undefined, 0)[LENGTH]){ $split = function(separator, limit){ return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); }; } // 21.1.3.17 String.prototype.split(separator, limit) return [function split(separator, limit){ var O = defined(this) , fn = separator == undefined ? undefined : separator[SPLIT]; return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); }, $split]; }); },{"./_fix-re-wks":37,"./_is-regexp":52}],221:[function(require,module,exports){ 'use strict'; require('./es6.regexp.flags'); var anObject = require('./_an-object') , $flags = require('./_flags') , DESCRIPTORS = require('./_descriptors') , TO_STRING = 'toString' , $toString = /./[TO_STRING]; var define = function(fn){ require('./_redefine')(RegExp.prototype, TO_STRING, fn, true); }; // 21.2.5.14 RegExp.prototype.toString() if(require('./_fails')(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){ define(function toString(){ var R = anObject(this); return '/'.concat(R.source, '/', 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); }); // FF44- RegExp#toString has a wrong name } else if($toString.name != TO_STRING){ define(function toString(){ return $toString.call(this); }); } },{"./_an-object":9,"./_descriptors":30,"./_fails":36,"./_flags":38,"./_redefine":89,"./es6.regexp.flags":216}],222:[function(require,module,exports){ 'use strict'; var strong = require('./_collection-strong'); // 23.2 Set Objects module.exports = require('./_collection')('Set', function(get){ return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.2.3.1 Set.prototype.add(value) add: function add(value){ return strong.def(this, value = value === 0 ? 0 : value, value); } }, strong); },{"./_collection":24,"./_collection-strong":21}],223:[function(require,module,exports){ 'use strict'; // B.2.3.2 String.prototype.anchor(name) require('./_string-html')('anchor', function(createHTML){ return function anchor(name){ return createHTML(this, 'a', 'name', name); } }); },{"./_string-html":101}],224:[function(require,module,exports){ 'use strict'; // B.2.3.3 String.prototype.big() require('./_string-html')('big', function(createHTML){ return function big(){ return createHTML(this, 'big', '', ''); } }); },{"./_string-html":101}],225:[function(require,module,exports){ 'use strict'; // B.2.3.4 String.prototype.blink() require('./_string-html')('blink', function(createHTML){ return function blink(){ return createHTML(this, 'blink', '', ''); } }); },{"./_string-html":101}],226:[function(require,module,exports){ 'use strict'; // B.2.3.5 String.prototype.bold() require('./_string-html')('bold', function(createHTML){ return function bold(){ return createHTML(this, 'b', '', ''); } }); },{"./_string-html":101}],227:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $at = require('./_string-at')(false); $export($export.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: function codePointAt(pos){ return $at(this, pos); } }); },{"./_export":34,"./_string-at":99}],228:[function(require,module,exports){ // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) 'use strict'; var $export = require('./_export') , toLength = require('./_to-length') , context = require('./_string-context') , ENDS_WITH = 'endsWith' , $endsWith = ''[ENDS_WITH]; $export($export.P + $export.F * require('./_fails-is-regexp')(ENDS_WITH), 'String', { endsWith: function endsWith(searchString /*, endPosition = @length */){ var that = context(this, searchString, ENDS_WITH) , endPosition = arguments.length > 1 ? arguments[1] : undefined , len = toLength(that.length) , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len) , search = String(searchString); return $endsWith ? $endsWith.call(that, search, end) : that.slice(end - search.length, end) === search; } }); },{"./_export":34,"./_fails-is-regexp":35,"./_string-context":100,"./_to-length":110}],229:[function(require,module,exports){ 'use strict'; // B.2.3.6 String.prototype.fixed() require('./_string-html')('fixed', function(createHTML){ return function fixed(){ return createHTML(this, 'tt', '', ''); } }); },{"./_string-html":101}],230:[function(require,module,exports){ 'use strict'; // B.2.3.7 String.prototype.fontcolor(color) require('./_string-html')('fontcolor', function(createHTML){ return function fontcolor(color){ return createHTML(this, 'font', 'color', color); } }); },{"./_string-html":101}],231:[function(require,module,exports){ 'use strict'; // B.2.3.8 String.prototype.fontsize(size) require('./_string-html')('fontsize', function(createHTML){ return function fontsize(size){ return createHTML(this, 'font', 'size', size); } }); },{"./_string-html":101}],232:[function(require,module,exports){ var $export = require('./_export') , toIndex = require('./_to-index') , fromCharCode = String.fromCharCode , $fromCodePoint = String.fromCodePoint; // length should be 1, old FF problem $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars var res = [] , aLen = arguments.length , i = 0 , code; while(aLen > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); } }); },{"./_export":34,"./_to-index":107}],233:[function(require,module,exports){ // 21.1.3.7 String.prototype.includes(searchString, position = 0) 'use strict'; var $export = require('./_export') , context = require('./_string-context') , INCLUDES = 'includes'; $export($export.P + $export.F * require('./_fails-is-regexp')(INCLUDES), 'String', { includes: function includes(searchString /*, position = 0 */){ return !!~context(this, searchString, INCLUDES) .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); } }); },{"./_export":34,"./_fails-is-regexp":35,"./_string-context":100}],234:[function(require,module,exports){ 'use strict'; // B.2.3.9 String.prototype.italics() require('./_string-html')('italics', function(createHTML){ return function italics(){ return createHTML(this, 'i', '', ''); } }); },{"./_string-html":101}],235:[function(require,module,exports){ 'use strict'; var $at = require('./_string-at')(true); // 21.1.3.27 String.prototype[@@iterator]() require('./_iter-define')(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); },{"./_iter-define":55,"./_string-at":99}],236:[function(require,module,exports){ 'use strict'; // B.2.3.10 String.prototype.link(url) require('./_string-html')('link', function(createHTML){ return function link(url){ return createHTML(this, 'a', 'href', url); } }); },{"./_string-html":101}],237:[function(require,module,exports){ var $export = require('./_export') , toIObject = require('./_to-iobject') , toLength = require('./_to-length'); $export($export.S, 'String', { // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function raw(callSite){ var tpl = toIObject(callSite.raw) , len = toLength(tpl.length) , aLen = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(tpl[i++])); if(i < aLen)res.push(String(arguments[i])); } return res.join(''); } }); },{"./_export":34,"./_to-iobject":109,"./_to-length":110}],238:[function(require,module,exports){ var $export = require('./_export'); $export($export.P, 'String', { // 21.1.3.13 String.prototype.repeat(count) repeat: require('./_string-repeat') }); },{"./_export":34,"./_string-repeat":103}],239:[function(require,module,exports){ 'use strict'; // B.2.3.11 String.prototype.small() require('./_string-html')('small', function(createHTML){ return function small(){ return createHTML(this, 'small', '', ''); } }); },{"./_string-html":101}],240:[function(require,module,exports){ // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) 'use strict'; var $export = require('./_export') , toLength = require('./_to-length') , context = require('./_string-context') , STARTS_WITH = 'startsWith' , $startsWith = ''[STARTS_WITH]; $export($export.P + $export.F * require('./_fails-is-regexp')(STARTS_WITH), 'String', { startsWith: function startsWith(searchString /*, position = 0 */){ var that = context(this, searchString, STARTS_WITH) , index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)) , search = String(searchString); return $startsWith ? $startsWith.call(that, search, index) : that.slice(index, index + search.length) === search; } }); },{"./_export":34,"./_fails-is-regexp":35,"./_string-context":100,"./_to-length":110}],241:[function(require,module,exports){ 'use strict'; // B.2.3.12 String.prototype.strike() require('./_string-html')('strike', function(createHTML){ return function strike(){ return createHTML(this, 'strike', '', ''); } }); },{"./_string-html":101}],242:[function(require,module,exports){ 'use strict'; // B.2.3.13 String.prototype.sub() require('./_string-html')('sub', function(createHTML){ return function sub(){ return createHTML(this, 'sub', '', ''); } }); },{"./_string-html":101}],243:[function(require,module,exports){ 'use strict'; // B.2.3.14 String.prototype.sup() require('./_string-html')('sup', function(createHTML){ return function sup(){ return createHTML(this, 'sup', '', ''); } }); },{"./_string-html":101}],244:[function(require,module,exports){ 'use strict'; // 21.1.3.25 String.prototype.trim() require('./_string-trim')('trim', function($trim){ return function trim(){ return $trim(this, 3); }; }); },{"./_string-trim":104}],245:[function(require,module,exports){ 'use strict'; // ECMAScript 6 symbols shim var global = require('./_global') , has = require('./_has') , DESCRIPTORS = require('./_descriptors') , $export = require('./_export') , redefine = require('./_redefine') , META = require('./_meta').KEY , $fails = require('./_fails') , shared = require('./_shared') , setToStringTag = require('./_set-to-string-tag') , uid = require('./_uid') , wks = require('./_wks') , wksExt = require('./_wks-ext') , wksDefine = require('./_wks-define') , keyOf = require('./_keyof') , enumKeys = require('./_enum-keys') , isArray = require('./_is-array') , anObject = require('./_an-object') , toIObject = require('./_to-iobject') , toPrimitive = require('./_to-primitive') , createDesc = require('./_property-desc') , _create = require('./_object-create') , gOPNExt = require('./_object-gopn-ext') , $GOPD = require('./_object-gopd') , $DP = require('./_object-dp') , $keys = require('./_object-keys') , gOPD = $GOPD.f , dP = $DP.f , gOPN = gOPNExt.f , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , PROTOTYPE = 'prototype' , HIDDEN = wks('_hidden') , TO_PRIMITIVE = wks('toPrimitive') , isEnum = {}.propertyIsEnumerable , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , OPSymbols = shared('op-symbols') , ObjectProto = Object[PROTOTYPE] , USE_NATIVE = typeof $Symbol == 'function' , QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(dP({}, 'a', { get: function(){ return dP(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = gOPD(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; dP(it, key, D); if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); } : dP; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ return typeof it == 'symbol'; } : function(it){ return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D){ if(it === ObjectProto)$defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if(has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key = toPrimitive(key, true)); if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ it = toIObject(it); key = toPrimitive(key, true); if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; var D = gOPD(it, key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = gOPN(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var IS_OP = it === ObjectProto , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function(value){ if(this === ObjectProto)$set.call(OPSymbols, value); if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString(){ return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; require('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames; require('./_object-pie').f = $propertyIsEnumerable; require('./_object-gops').f = $getOwnPropertySymbols; if(DESCRIPTORS && !require('./_library')){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function(name){ return wrap(wks(name)); } } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); for(var symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ if(isSymbol(key))return keyOf(SymbolRegistry, key); throw TypeError(key + ' is not a symbol!'); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , replacer, $replacer; while(arguments.length > i)args.push(arguments[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || require('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); },{"./_an-object":9,"./_descriptors":30,"./_enum-keys":33,"./_export":34,"./_fails":36,"./_global":40,"./_has":41,"./_hide":42,"./_is-array":49,"./_keyof":59,"./_library":60,"./_meta":64,"./_object-create":68,"./_object-dp":69,"./_object-gopd":72,"./_object-gopn":74,"./_object-gopn-ext":73,"./_object-gops":75,"./_object-keys":78,"./_object-pie":79,"./_property-desc":87,"./_redefine":89,"./_set-to-string-tag":94,"./_shared":96,"./_to-iobject":109,"./_to-primitive":112,"./_uid":116,"./_wks":119,"./_wks-define":117,"./_wks-ext":118}],246:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , $typed = require('./_typed') , buffer = require('./_typed-buffer') , anObject = require('./_an-object') , toIndex = require('./_to-index') , toLength = require('./_to-length') , isObject = require('./_is-object') , ArrayBuffer = require('./_global').ArrayBuffer , speciesConstructor = require('./_species-constructor') , $ArrayBuffer = buffer.ArrayBuffer , $DataView = buffer.DataView , $isView = $typed.ABV && ArrayBuffer.isView , $slice = $ArrayBuffer.prototype.slice , VIEW = $typed.VIEW , ARRAY_BUFFER = 'ArrayBuffer'; $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer}); $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { // 24.1.3.1 ArrayBuffer.isView(arg) isView: function isView(it){ return $isView && $isView(it) || isObject(it) && VIEW in it; } }); $export($export.P + $export.U + $export.F * require('./_fails')(function(){ return !new $ArrayBuffer(2).slice(1, undefined).byteLength; }), ARRAY_BUFFER, { // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) slice: function slice(start, end){ if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix var len = anObject(this).byteLength , first = toIndex(start, len) , final = toIndex(end === undefined ? len : end, len) , result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first)) , viewS = new $DataView(this) , viewT = new $DataView(result) , index = 0; while(first < final){ viewT.setUint8(index++, viewS.getUint8(first++)); } return result; } }); require('./_set-species')(ARRAY_BUFFER); },{"./_an-object":9,"./_export":34,"./_fails":36,"./_global":40,"./_is-object":51,"./_set-species":93,"./_species-constructor":97,"./_to-index":107,"./_to-length":110,"./_typed":115,"./_typed-buffer":114}],247:[function(require,module,exports){ var $export = require('./_export'); $export($export.G + $export.W + $export.F * !require('./_typed').ABV, { DataView: require('./_typed-buffer').DataView }); },{"./_export":34,"./_typed":115,"./_typed-buffer":114}],248:[function(require,module,exports){ require('./_typed-array')('Float32', 4, function(init){ return function Float32Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"./_typed-array":113}],249:[function(require,module,exports){ require('./_typed-array')('Float64', 8, function(init){ return function Float64Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"./_typed-array":113}],250:[function(require,module,exports){ require('./_typed-array')('Int16', 2, function(init){ return function Int16Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"./_typed-array":113}],251:[function(require,module,exports){ require('./_typed-array')('Int32', 4, function(init){ return function Int32Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"./_typed-array":113}],252:[function(require,module,exports){ require('./_typed-array')('Int8', 1, function(init){ return function Int8Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"./_typed-array":113}],253:[function(require,module,exports){ require('./_typed-array')('Uint16', 2, function(init){ return function Uint16Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"./_typed-array":113}],254:[function(require,module,exports){ require('./_typed-array')('Uint32', 4, function(init){ return function Uint32Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"./_typed-array":113}],255:[function(require,module,exports){ require('./_typed-array')('Uint8', 1, function(init){ return function Uint8Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"./_typed-array":113}],256:[function(require,module,exports){ require('./_typed-array')('Uint8', 1, function(init){ return function Uint8ClampedArray(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }, true); },{"./_typed-array":113}],257:[function(require,module,exports){ 'use strict'; var each = require('./_array-methods')(0) , redefine = require('./_redefine') , meta = require('./_meta') , assign = require('./_object-assign') , weak = require('./_collection-weak') , isObject = require('./_is-object') , getWeak = meta.getWeak , isExtensible = Object.isExtensible , uncaughtFrozenStore = weak.ufstore , tmp = {} , InternalMap; var wrapper = function(get){ return function WeakMap(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }; var methods = { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).get(key); return data ? data[this._i] : undefined; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return weak.def(this, key, value); } }; // 23.3 WeakMap Objects var $WeakMap = module.exports = require('./_collection')('WeakMap', wrapper, methods, weak, true, true); // IE11 WeakMap frozen keys fix if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ InternalMap = weak.getConstructor(wrapper); assign(InternalMap.prototype, methods); meta.NEED = true; each(['delete', 'has', 'get', 'set'], function(key){ var proto = $WeakMap.prototype , method = proto[key]; redefine(proto, key, function(a, b){ // store frozen objects on internal weakmap shim if(isObject(a) && !isExtensible(a)){ if(!this._f)this._f = new InternalMap; var result = this._f[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }); }); } },{"./_array-methods":14,"./_collection":24,"./_collection-weak":23,"./_is-object":51,"./_meta":64,"./_object-assign":67,"./_redefine":89}],258:[function(require,module,exports){ 'use strict'; var weak = require('./_collection-weak'); // 23.4 WeakSet Objects require('./_collection')('WeakSet', function(get){ return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value){ return weak.def(this, value, true); } }, weak, false, true); },{"./_collection":24,"./_collection-weak":23}],259:[function(require,module,exports){ 'use strict'; // https://github.com/tc39/Array.prototype.includes var $export = require('./_export') , $includes = require('./_array-includes')(true); $export($export.P, 'Array', { includes: function includes(el /*, fromIndex = 0 */){ return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); require('./_add-to-unscopables')('includes'); },{"./_add-to-unscopables":7,"./_array-includes":13,"./_export":34}],260:[function(require,module,exports){ // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask var $export = require('./_export') , microtask = require('./_microtask')() , process = require('./_global').process , isNode = require('./_cof')(process) == 'process'; $export($export.G, { asap: function asap(fn){ var domain = isNode && process.domain; microtask(domain ? domain.bind(fn) : fn); } }); },{"./_cof":20,"./_export":34,"./_global":40,"./_microtask":66}],261:[function(require,module,exports){ // https://github.com/ljharb/proposal-is-error var $export = require('./_export') , cof = require('./_cof'); $export($export.S, 'Error', { isError: function isError(it){ return cof(it) === 'Error'; } }); },{"./_cof":20,"./_export":34}],262:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = require('./_export'); $export($export.P + $export.R, 'Map', {toJSON: require('./_collection-to-json')('Map')}); },{"./_collection-to-json":22,"./_export":34}],263:[function(require,module,exports){ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = require('./_export'); $export($export.S, 'Math', { iaddh: function iaddh(x0, x1, y0, y1){ var $x0 = x0 >>> 0 , $x1 = x1 >>> 0 , $y0 = y0 >>> 0; return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; } }); },{"./_export":34}],264:[function(require,module,exports){ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = require('./_export'); $export($export.S, 'Math', { imulh: function imulh(u, v){ var UINT16 = 0xffff , $u = +u , $v = +v , u0 = $u & UINT16 , v0 = $v & UINT16 , u1 = $u >> 16 , v1 = $v >> 16 , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); } }); },{"./_export":34}],265:[function(require,module,exports){ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = require('./_export'); $export($export.S, 'Math', { isubh: function isubh(x0, x1, y0, y1){ var $x0 = x0 >>> 0 , $x1 = x1 >>> 0 , $y0 = y0 >>> 0; return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; } }); },{"./_export":34}],266:[function(require,module,exports){ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = require('./_export'); $export($export.S, 'Math', { umulh: function umulh(u, v){ var UINT16 = 0xffff , $u = +u , $v = +v , u0 = $u & UINT16 , v0 = $v & UINT16 , u1 = $u >>> 16 , v1 = $v >>> 16 , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); } }); },{"./_export":34}],267:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , toObject = require('./_to-object') , aFunction = require('./_a-function') , $defineProperty = require('./_object-dp'); // B.2.2.2 Object.prototype.__defineGetter__(P, getter) require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', { __defineGetter__: function __defineGetter__(P, getter){ $defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true}); } }); },{"./_a-function":5,"./_descriptors":30,"./_export":34,"./_object-dp":69,"./_object-forced-pam":71,"./_to-object":111}],268:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , toObject = require('./_to-object') , aFunction = require('./_a-function') , $defineProperty = require('./_object-dp'); // B.2.2.3 Object.prototype.__defineSetter__(P, setter) require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', { __defineSetter__: function __defineSetter__(P, setter){ $defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true}); } }); },{"./_a-function":5,"./_descriptors":30,"./_export":34,"./_object-dp":69,"./_object-forced-pam":71,"./_to-object":111}],269:[function(require,module,exports){ // https://github.com/tc39/proposal-object-values-entries var $export = require('./_export') , $entries = require('./_object-to-array')(true); $export($export.S, 'Object', { entries: function entries(it){ return $entries(it); } }); },{"./_export":34,"./_object-to-array":81}],270:[function(require,module,exports){ // https://github.com/tc39/proposal-object-getownpropertydescriptors var $export = require('./_export') , ownKeys = require('./_own-keys') , toIObject = require('./_to-iobject') , gOPD = require('./_object-gopd') , createProperty = require('./_create-property'); $export($export.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ var O = toIObject(object) , getDesc = gOPD.f , keys = ownKeys(O) , result = {} , i = 0 , key; while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key)); return result; } }); },{"./_create-property":26,"./_export":34,"./_object-gopd":72,"./_own-keys":82,"./_to-iobject":109}],271:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , toObject = require('./_to-object') , toPrimitive = require('./_to-primitive') , getPrototypeOf = require('./_object-gpo') , getOwnPropertyDescriptor = require('./_object-gopd').f; // B.2.2.4 Object.prototype.__lookupGetter__(P) require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', { __lookupGetter__: function __lookupGetter__(P){ var O = toObject(this) , K = toPrimitive(P, true) , D; do { if(D = getOwnPropertyDescriptor(O, K))return D.get; } while(O = getPrototypeOf(O)); } }); },{"./_descriptors":30,"./_export":34,"./_object-forced-pam":71,"./_object-gopd":72,"./_object-gpo":76,"./_to-object":111,"./_to-primitive":112}],272:[function(require,module,exports){ 'use strict'; var $export = require('./_export') , toObject = require('./_to-object') , toPrimitive = require('./_to-primitive') , getPrototypeOf = require('./_object-gpo') , getOwnPropertyDescriptor = require('./_object-gopd').f; // B.2.2.5 Object.prototype.__lookupSetter__(P) require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', { __lookupSetter__: function __lookupSetter__(P){ var O = toObject(this) , K = toPrimitive(P, true) , D; do { if(D = getOwnPropertyDescriptor(O, K))return D.set; } while(O = getPrototypeOf(O)); } }); },{"./_descriptors":30,"./_export":34,"./_object-forced-pam":71,"./_object-gopd":72,"./_object-gpo":76,"./_to-object":111,"./_to-primitive":112}],273:[function(require,module,exports){ // https://github.com/tc39/proposal-object-values-entries var $export = require('./_export') , $values = require('./_object-to-array')(false); $export($export.S, 'Object', { values: function values(it){ return $values(it); } }); },{"./_export":34,"./_object-to-array":81}],274:[function(require,module,exports){ 'use strict'; // https://github.com/zenparsing/es-observable var $export = require('./_export') , global = require('./_global') , core = require('./_core') , microtask = require('./_microtask')() , OBSERVABLE = require('./_wks')('observable') , aFunction = require('./_a-function') , anObject = require('./_an-object') , anInstance = require('./_an-instance') , redefineAll = require('./_redefine-all') , hide = require('./_hide') , forOf = require('./_for-of') , RETURN = forOf.RETURN; var getMethod = function(fn){ return fn == null ? undefined : aFunction(fn); }; var cleanupSubscription = function(subscription){ var cleanup = subscription._c; if(cleanup){ subscription._c = undefined; cleanup(); } }; var subscriptionClosed = function(subscription){ return subscription._o === undefined; }; var closeSubscription = function(subscription){ if(!subscriptionClosed(subscription)){ subscription._o = undefined; cleanupSubscription(subscription); } }; var Subscription = function(observer, subscriber){ anObject(observer); this._c = undefined; this._o = observer; observer = new SubscriptionObserver(this); try { var cleanup = subscriber(observer) , subscription = cleanup; if(cleanup != null){ if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); }; else aFunction(cleanup); this._c = cleanup; } } catch(e){ observer.error(e); return; } if(subscriptionClosed(this))cleanupSubscription(this); }; Subscription.prototype = redefineAll({}, { unsubscribe: function unsubscribe(){ closeSubscription(this); } }); var SubscriptionObserver = function(subscription){ this._s = subscription; }; SubscriptionObserver.prototype = redefineAll({}, { next: function next(value){ var subscription = this._s; if(!subscriptionClosed(subscription)){ var observer = subscription._o; try { var m = getMethod(observer.next); if(m)return m.call(observer, value); } catch(e){ try { closeSubscription(subscription); } finally { throw e; } } } }, error: function error(value){ var subscription = this._s; if(subscriptionClosed(subscription))throw value; var observer = subscription._o; subscription._o = undefined; try { var m = getMethod(observer.error); if(!m)throw value; value = m.call(observer, value); } catch(e){ try { cleanupSubscription(subscription); } finally { throw e; } } cleanupSubscription(subscription); return value; }, complete: function complete(value){ var subscription = this._s; if(!subscriptionClosed(subscription)){ var observer = subscription._o; subscription._o = undefined; try { var m = getMethod(observer.complete); value = m ? m.call(observer, value) : undefined; } catch(e){ try { cleanupSubscription(subscription); } finally { throw e; } } cleanupSubscription(subscription); return value; } } }); var $Observable = function Observable(subscriber){ anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); }; redefineAll($Observable.prototype, { subscribe: function subscribe(observer){ return new Subscription(observer, this._f); }, forEach: function forEach(fn){ var that = this; return new (core.Promise || global.Promise)(function(resolve, reject){ aFunction(fn); var subscription = that.subscribe({ next : function(value){ try { return fn(value); } catch(e){ reject(e); subscription.unsubscribe(); } }, error: reject, complete: resolve }); }); } }); redefineAll($Observable, { from: function from(x){ var C = typeof this === 'function' ? this : $Observable; var method = getMethod(anObject(x)[OBSERVABLE]); if(method){ var observable = anObject(method.call(x)); return observable.constructor === C ? observable : new C(function(observer){ return observable.subscribe(observer); }); } return new C(function(observer){ var done = false; microtask(function(){ if(!done){ try { if(forOf(x, false, function(it){ observer.next(it); if(done)return RETURN; }) === RETURN)return; } catch(e){ if(done)throw e; observer.error(e); return; } observer.complete(); } }); return function(){ done = true; }; }); }, of: function of(){ for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++]; return new (typeof this === 'function' ? this : $Observable)(function(observer){ var done = false; microtask(function(){ if(!done){ for(var i = 0; i < items.length; ++i){ observer.next(items[i]); if(done)return; } observer.complete(); } }); return function(){ done = true; }; }); } }); hide($Observable.prototype, OBSERVABLE, function(){ return this; }); $export($export.G, {Observable: $Observable}); require('./_set-species')('Observable'); },{"./_a-function":5,"./_an-instance":8,"./_an-object":9,"./_core":25,"./_export":34,"./_for-of":39,"./_global":40,"./_hide":42,"./_microtask":66,"./_redefine-all":88,"./_set-species":93,"./_wks":119}],275:[function(require,module,exports){ var metadata = require('./_metadata') , anObject = require('./_an-object') , toMetaKey = metadata.key , ordinaryDefineOwnMetadata = metadata.set; metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){ ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); }}); },{"./_an-object":9,"./_metadata":65}],276:[function(require,module,exports){ var metadata = require('./_metadata') , anObject = require('./_an-object') , toMetaKey = metadata.key , getOrCreateMetadataMap = metadata.map , store = metadata.store; metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){ var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]) , metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false; if(metadataMap.size)return true; var targetMetadata = store.get(target); targetMetadata['delete'](targetKey); return !!targetMetadata.size || store['delete'](target); }}); },{"./_an-object":9,"./_metadata":65}],277:[function(require,module,exports){ var Set = require('./es6.set') , from = require('./_array-from-iterable') , metadata = require('./_metadata') , anObject = require('./_an-object') , getPrototypeOf = require('./_object-gpo') , ordinaryOwnMetadataKeys = metadata.keys , toMetaKey = metadata.key; var ordinaryMetadataKeys = function(O, P){ var oKeys = ordinaryOwnMetadataKeys(O, P) , parent = getPrototypeOf(O); if(parent === null)return oKeys; var pKeys = ordinaryMetadataKeys(parent, P); return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; }; metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){ return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); }}); },{"./_an-object":9,"./_array-from-iterable":12,"./_metadata":65,"./_object-gpo":76,"./es6.set":222}],278:[function(require,module,exports){ var metadata = require('./_metadata') , anObject = require('./_an-object') , getPrototypeOf = require('./_object-gpo') , ordinaryHasOwnMetadata = metadata.has , ordinaryGetOwnMetadata = metadata.get , toMetaKey = metadata.key; var ordinaryGetMetadata = function(MetadataKey, O, P){ var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P); var parent = getPrototypeOf(O); return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; }; metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){ return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); },{"./_an-object":9,"./_metadata":65,"./_object-gpo":76}],279:[function(require,module,exports){ var metadata = require('./_metadata') , anObject = require('./_an-object') , ordinaryOwnMetadataKeys = metadata.keys , toMetaKey = metadata.key; metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){ return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); }}); },{"./_an-object":9,"./_metadata":65}],280:[function(require,module,exports){ var metadata = require('./_metadata') , anObject = require('./_an-object') , ordinaryGetOwnMetadata = metadata.get , toMetaKey = metadata.key; metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){ return ordinaryGetOwnMetadata(metadataKey, anObject(target) , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); },{"./_an-object":9,"./_metadata":65}],281:[function(require,module,exports){ var metadata = require('./_metadata') , anObject = require('./_an-object') , getPrototypeOf = require('./_object-gpo') , ordinaryHasOwnMetadata = metadata.has , toMetaKey = metadata.key; var ordinaryHasMetadata = function(MetadataKey, O, P){ var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); if(hasOwn)return true; var parent = getPrototypeOf(O); return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; }; metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){ return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); },{"./_an-object":9,"./_metadata":65,"./_object-gpo":76}],282:[function(require,module,exports){ var metadata = require('./_metadata') , anObject = require('./_an-object') , ordinaryHasOwnMetadata = metadata.has , toMetaKey = metadata.key; metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){ return ordinaryHasOwnMetadata(metadataKey, anObject(target) , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); },{"./_an-object":9,"./_metadata":65}],283:[function(require,module,exports){ var metadata = require('./_metadata') , anObject = require('./_an-object') , aFunction = require('./_a-function') , toMetaKey = metadata.key , ordinaryDefineOwnMetadata = metadata.set; metadata.exp({metadata: function metadata(metadataKey, metadataValue){ return function decorator(target, targetKey){ ordinaryDefineOwnMetadata( metadataKey, metadataValue, (targetKey !== undefined ? anObject : aFunction)(target), toMetaKey(targetKey) ); }; }}); },{"./_a-function":5,"./_an-object":9,"./_metadata":65}],284:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = require('./_export'); $export($export.P + $export.R, 'Set', {toJSON: require('./_collection-to-json')('Set')}); },{"./_collection-to-json":22,"./_export":34}],285:[function(require,module,exports){ 'use strict'; // https://github.com/mathiasbynens/String.prototype.at var $export = require('./_export') , $at = require('./_string-at')(true); $export($export.P, 'String', { at: function at(pos){ return $at(this, pos); } }); },{"./_export":34,"./_string-at":99}],286:[function(require,module,exports){ 'use strict'; // https://tc39.github.io/String.prototype.matchAll/ var $export = require('./_export') , defined = require('./_defined') , toLength = require('./_to-length') , isRegExp = require('./_is-regexp') , getFlags = require('./_flags') , RegExpProto = RegExp.prototype; var $RegExpStringIterator = function(regexp, string){ this._r = regexp; this._s = string; }; require('./_iter-create')($RegExpStringIterator, 'RegExp String', function next(){ var match = this._r.exec(this._s); return {value: match, done: match === null}; }); $export($export.P, 'String', { matchAll: function matchAll(regexp){ defined(this); if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!'); var S = String(this) , flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp) , rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); rx.lastIndex = toLength(regexp.lastIndex); return new $RegExpStringIterator(rx, S); } }); },{"./_defined":29,"./_export":34,"./_flags":38,"./_is-regexp":52,"./_iter-create":54,"./_to-length":110}],287:[function(require,module,exports){ 'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = require('./_export') , $pad = require('./_string-pad'); $export($export.P, 'String', { padEnd: function padEnd(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); } }); },{"./_export":34,"./_string-pad":102}],288:[function(require,module,exports){ 'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = require('./_export') , $pad = require('./_string-pad'); $export($export.P, 'String', { padStart: function padStart(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); } }); },{"./_export":34,"./_string-pad":102}],289:[function(require,module,exports){ 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim require('./_string-trim')('trimLeft', function($trim){ return function trimLeft(){ return $trim(this, 1); }; }, 'trimStart'); },{"./_string-trim":104}],290:[function(require,module,exports){ 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim require('./_string-trim')('trimRight', function($trim){ return function trimRight(){ return $trim(this, 2); }; }, 'trimEnd'); },{"./_string-trim":104}],291:[function(require,module,exports){ require('./_wks-define')('asyncIterator'); },{"./_wks-define":117}],292:[function(require,module,exports){ require('./_wks-define')('observable'); },{"./_wks-define":117}],293:[function(require,module,exports){ // https://github.com/ljharb/proposal-global var $export = require('./_export'); $export($export.S, 'System', {global: require('./_global')}); },{"./_export":34,"./_global":40}],294:[function(require,module,exports){ var $iterators = require('./es6.array.iterator') , redefine = require('./_redefine') , global = require('./_global') , hide = require('./_hide') , Iterators = require('./_iterators') , wks = require('./_wks') , ITERATOR = wks('iterator') , TO_STRING_TAG = wks('toStringTag') , ArrayValues = Iterators.Array; for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = global[NAME] , proto = Collection && Collection.prototype , key; if(proto){ if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues); if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = ArrayValues; for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true); } } },{"./_global":40,"./_hide":42,"./_iterators":58,"./_redefine":89,"./_wks":119,"./es6.array.iterator":132}],295:[function(require,module,exports){ var $export = require('./_export') , $task = require('./_task'); $export($export.G + $export.B, { setImmediate: $task.set, clearImmediate: $task.clear }); },{"./_export":34,"./_task":106}],296:[function(require,module,exports){ // ie9- setTimeout & setInterval additional parameters fix var global = require('./_global') , $export = require('./_export') , invoke = require('./_invoke') , partial = require('./_partial') , navigator = global.navigator , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check var wrap = function(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke( partial, [].slice.call(arguments, 2), typeof fn == 'function' ? fn : Function(fn) ), time); } : set; }; $export($export.G + $export.B + $export.F * MSIE, { setTimeout: wrap(global.setTimeout), setInterval: wrap(global.setInterval) }); },{"./_export":34,"./_global":40,"./_invoke":46,"./_partial":85}],297:[function(require,module,exports){ require('./modules/es6.symbol'); require('./modules/es6.object.create'); require('./modules/es6.object.define-property'); require('./modules/es6.object.define-properties'); require('./modules/es6.object.get-own-property-descriptor'); require('./modules/es6.object.get-prototype-of'); require('./modules/es6.object.keys'); require('./modules/es6.object.get-own-property-names'); require('./modules/es6.object.freeze'); require('./modules/es6.object.seal'); require('./modules/es6.object.prevent-extensions'); require('./modules/es6.object.is-frozen'); require('./modules/es6.object.is-sealed'); require('./modules/es6.object.is-extensible'); require('./modules/es6.object.assign'); require('./modules/es6.object.is'); require('./modules/es6.object.set-prototype-of'); require('./modules/es6.object.to-string'); require('./modules/es6.function.bind'); require('./modules/es6.function.name'); require('./modules/es6.function.has-instance'); require('./modules/es6.parse-int'); require('./modules/es6.parse-float'); require('./modules/es6.number.constructor'); require('./modules/es6.number.to-fixed'); require('./modules/es6.number.to-precision'); require('./modules/es6.number.epsilon'); require('./modules/es6.number.is-finite'); require('./modules/es6.number.is-integer'); require('./modules/es6.number.is-nan'); require('./modules/es6.number.is-safe-integer'); require('./modules/es6.number.max-safe-integer'); require('./modules/es6.number.min-safe-integer'); require('./modules/es6.number.parse-float'); require('./modules/es6.number.parse-int'); require('./modules/es6.math.acosh'); require('./modules/es6.math.asinh'); require('./modules/es6.math.atanh'); require('./modules/es6.math.cbrt'); require('./modules/es6.math.clz32'); require('./modules/es6.math.cosh'); require('./modules/es6.math.expm1'); require('./modules/es6.math.fround'); require('./modules/es6.math.hypot'); require('./modules/es6.math.imul'); require('./modules/es6.math.log10'); require('./modules/es6.math.log1p'); require('./modules/es6.math.log2'); require('./modules/es6.math.sign'); require('./modules/es6.math.sinh'); require('./modules/es6.math.tanh'); require('./modules/es6.math.trunc'); require('./modules/es6.string.from-code-point'); require('./modules/es6.string.raw'); require('./modules/es6.string.trim'); require('./modules/es6.string.iterator'); require('./modules/es6.string.code-point-at'); require('./modules/es6.string.ends-with'); require('./modules/es6.string.includes'); require('./modules/es6.string.repeat'); require('./modules/es6.string.starts-with'); require('./modules/es6.string.anchor'); require('./modules/es6.string.big'); require('./modules/es6.string.blink'); require('./modules/es6.string.bold'); require('./modules/es6.string.fixed'); require('./modules/es6.string.fontcolor'); require('./modules/es6.string.fontsize'); require('./modules/es6.string.italics'); require('./modules/es6.string.link'); require('./modules/es6.string.small'); require('./modules/es6.string.strike'); require('./modules/es6.string.sub'); require('./modules/es6.string.sup'); require('./modules/es6.date.now'); require('./modules/es6.date.to-json'); require('./modules/es6.date.to-iso-string'); require('./modules/es6.date.to-string'); require('./modules/es6.date.to-primitive'); require('./modules/es6.array.is-array'); require('./modules/es6.array.from'); require('./modules/es6.array.of'); require('./modules/es6.array.join'); require('./modules/es6.array.slice'); require('./modules/es6.array.sort'); require('./modules/es6.array.for-each'); require('./modules/es6.array.map'); require('./modules/es6.array.filter'); require('./modules/es6.array.some'); require('./modules/es6.array.every'); require('./modules/es6.array.reduce'); require('./modules/es6.array.reduce-right'); require('./modules/es6.array.index-of'); require('./modules/es6.array.last-index-of'); require('./modules/es6.array.copy-within'); require('./modules/es6.array.fill'); require('./modules/es6.array.find'); require('./modules/es6.array.find-index'); require('./modules/es6.array.species'); require('./modules/es6.array.iterator'); require('./modules/es6.regexp.constructor'); require('./modules/es6.regexp.to-string'); require('./modules/es6.regexp.flags'); require('./modules/es6.regexp.match'); require('./modules/es6.regexp.replace'); require('./modules/es6.regexp.search'); require('./modules/es6.regexp.split'); require('./modules/es6.promise'); require('./modules/es6.map'); require('./modules/es6.set'); require('./modules/es6.weak-map'); require('./modules/es6.weak-set'); require('./modules/es6.typed.array-buffer'); require('./modules/es6.typed.data-view'); require('./modules/es6.typed.int8-array'); require('./modules/es6.typed.uint8-array'); require('./modules/es6.typed.uint8-clamped-array'); require('./modules/es6.typed.int16-array'); require('./modules/es6.typed.uint16-array'); require('./modules/es6.typed.int32-array'); require('./modules/es6.typed.uint32-array'); require('./modules/es6.typed.float32-array'); require('./modules/es6.typed.float64-array'); require('./modules/es6.reflect.apply'); require('./modules/es6.reflect.construct'); require('./modules/es6.reflect.define-property'); require('./modules/es6.reflect.delete-property'); require('./modules/es6.reflect.enumerate'); require('./modules/es6.reflect.get'); require('./modules/es6.reflect.get-own-property-descriptor'); require('./modules/es6.reflect.get-prototype-of'); require('./modules/es6.reflect.has'); require('./modules/es6.reflect.is-extensible'); require('./modules/es6.reflect.own-keys'); require('./modules/es6.reflect.prevent-extensions'); require('./modules/es6.reflect.set'); require('./modules/es6.reflect.set-prototype-of'); require('./modules/es7.array.includes'); require('./modules/es7.string.at'); require('./modules/es7.string.pad-start'); require('./modules/es7.string.pad-end'); require('./modules/es7.string.trim-left'); require('./modules/es7.string.trim-right'); require('./modules/es7.string.match-all'); require('./modules/es7.symbol.async-iterator'); require('./modules/es7.symbol.observable'); require('./modules/es7.object.get-own-property-descriptors'); require('./modules/es7.object.values'); require('./modules/es7.object.entries'); require('./modules/es7.object.define-getter'); require('./modules/es7.object.define-setter'); require('./modules/es7.object.lookup-getter'); require('./modules/es7.object.lookup-setter'); require('./modules/es7.map.to-json'); require('./modules/es7.set.to-json'); require('./modules/es7.system.global'); require('./modules/es7.error.is-error'); require('./modules/es7.math.iaddh'); require('./modules/es7.math.isubh'); require('./modules/es7.math.imulh'); require('./modules/es7.math.umulh'); require('./modules/es7.reflect.define-metadata'); require('./modules/es7.reflect.delete-metadata'); require('./modules/es7.reflect.get-metadata'); require('./modules/es7.reflect.get-metadata-keys'); require('./modules/es7.reflect.get-own-metadata'); require('./modules/es7.reflect.get-own-metadata-keys'); require('./modules/es7.reflect.has-metadata'); require('./modules/es7.reflect.has-own-metadata'); require('./modules/es7.reflect.metadata'); require('./modules/es7.asap'); require('./modules/es7.observable'); require('./modules/web.timers'); require('./modules/web.immediate'); require('./modules/web.dom.iterable'); module.exports = require('./modules/_core'); },{"./modules/_core":25,"./modules/es6.array.copy-within":122,"./modules/es6.array.every":123,"./modules/es6.array.fill":124,"./modules/es6.array.filter":125,"./modules/es6.array.find":127,"./modules/es6.array.find-index":126,"./modules/es6.array.for-each":128,"./modules/es6.array.from":129,"./modules/es6.array.index-of":130,"./modules/es6.array.is-array":131,"./modules/es6.array.iterator":132,"./modules/es6.array.join":133,"./modules/es6.array.last-index-of":134,"./modules/es6.array.map":135,"./modules/es6.array.of":136,"./modules/es6.array.reduce":138,"./modules/es6.array.reduce-right":137,"./modules/es6.array.slice":139,"./modules/es6.array.some":140,"./modules/es6.array.sort":141,"./modules/es6.array.species":142,"./modules/es6.date.now":143,"./modules/es6.date.to-iso-string":144,"./modules/es6.date.to-json":145,"./modules/es6.date.to-primitive":146,"./modules/es6.date.to-string":147,"./modules/es6.function.bind":148,"./modules/es6.function.has-instance":149,"./modules/es6.function.name":150,"./modules/es6.map":151,"./modules/es6.math.acosh":152,"./modules/es6.math.asinh":153,"./modules/es6.math.atanh":154,"./modules/es6.math.cbrt":155,"./modules/es6.math.clz32":156,"./modules/es6.math.cosh":157,"./modules/es6.math.expm1":158,"./modules/es6.math.fround":159,"./modules/es6.math.hypot":160,"./modules/es6.math.imul":161,"./modules/es6.math.log10":162,"./modules/es6.math.log1p":163,"./modules/es6.math.log2":164,"./modules/es6.math.sign":165,"./modules/es6.math.sinh":166,"./modules/es6.math.tanh":167,"./modules/es6.math.trunc":168,"./modules/es6.number.constructor":169,"./modules/es6.number.epsilon":170,"./modules/es6.number.is-finite":171,"./modules/es6.number.is-integer":172,"./modules/es6.number.is-nan":173,"./modules/es6.number.is-safe-integer":174,"./modules/es6.number.max-safe-integer":175,"./modules/es6.number.min-safe-integer":176,"./modules/es6.number.parse-float":177,"./modules/es6.number.parse-int":178,"./modules/es6.number.to-fixed":179,"./modules/es6.number.to-precision":180,"./modules/es6.object.assign":181,"./modules/es6.object.create":182,"./modules/es6.object.define-properties":183,"./modules/es6.object.define-property":184,"./modules/es6.object.freeze":185,"./modules/es6.object.get-own-property-descriptor":186,"./modules/es6.object.get-own-property-names":187,"./modules/es6.object.get-prototype-of":188,"./modules/es6.object.is":192,"./modules/es6.object.is-extensible":189,"./modules/es6.object.is-frozen":190,"./modules/es6.object.is-sealed":191,"./modules/es6.object.keys":193,"./modules/es6.object.prevent-extensions":194,"./modules/es6.object.seal":195,"./modules/es6.object.set-prototype-of":196,"./modules/es6.object.to-string":197,"./modules/es6.parse-float":198,"./modules/es6.parse-int":199,"./modules/es6.promise":200,"./modules/es6.reflect.apply":201,"./modules/es6.reflect.construct":202,"./modules/es6.reflect.define-property":203,"./modules/es6.reflect.delete-property":204,"./modules/es6.reflect.enumerate":205,"./modules/es6.reflect.get":208,"./modules/es6.reflect.get-own-property-descriptor":206,"./modules/es6.reflect.get-prototype-of":207,"./modules/es6.reflect.has":209,"./modules/es6.reflect.is-extensible":210,"./modules/es6.reflect.own-keys":211,"./modules/es6.reflect.prevent-extensions":212,"./modules/es6.reflect.set":214,"./modules/es6.reflect.set-prototype-of":213,"./modules/es6.regexp.constructor":215,"./modules/es6.regexp.flags":216,"./modules/es6.regexp.match":217,"./modules/es6.regexp.replace":218,"./modules/es6.regexp.search":219,"./modules/es6.regexp.split":220,"./modules/es6.regexp.to-string":221,"./modules/es6.set":222,"./modules/es6.string.anchor":223,"./modules/es6.string.big":224,"./modules/es6.string.blink":225,"./modules/es6.string.bold":226,"./modules/es6.string.code-point-at":227,"./modules/es6.string.ends-with":228,"./modules/es6.string.fixed":229,"./modules/es6.string.fontcolor":230,"./modules/es6.string.fontsize":231,"./modules/es6.string.from-code-point":232,"./modules/es6.string.includes":233,"./modules/es6.string.italics":234,"./modules/es6.string.iterator":235,"./modules/es6.string.link":236,"./modules/es6.string.raw":237,"./modules/es6.string.repeat":238,"./modules/es6.string.small":239,"./modules/es6.string.starts-with":240,"./modules/es6.string.strike":241,"./modules/es6.string.sub":242,"./modules/es6.string.sup":243,"./modules/es6.string.trim":244,"./modules/es6.symbol":245,"./modules/es6.typed.array-buffer":246,"./modules/es6.typed.data-view":247,"./modules/es6.typed.float32-array":248,"./modules/es6.typed.float64-array":249,"./modules/es6.typed.int16-array":250,"./modules/es6.typed.int32-array":251,"./modules/es6.typed.int8-array":252,"./modules/es6.typed.uint16-array":253,"./modules/es6.typed.uint32-array":254,"./modules/es6.typed.uint8-array":255,"./modules/es6.typed.uint8-clamped-array":256,"./modules/es6.weak-map":257,"./modules/es6.weak-set":258,"./modules/es7.array.includes":259,"./modules/es7.asap":260,"./modules/es7.error.is-error":261,"./modules/es7.map.to-json":262,"./modules/es7.math.iaddh":263,"./modules/es7.math.imulh":264,"./modules/es7.math.isubh":265,"./modules/es7.math.umulh":266,"./modules/es7.object.define-getter":267,"./modules/es7.object.define-setter":268,"./modules/es7.object.entries":269,"./modules/es7.object.get-own-property-descriptors":270,"./modules/es7.object.lookup-getter":271,"./modules/es7.object.lookup-setter":272,"./modules/es7.object.values":273,"./modules/es7.observable":274,"./modules/es7.reflect.define-metadata":275,"./modules/es7.reflect.delete-metadata":276,"./modules/es7.reflect.get-metadata":278,"./modules/es7.reflect.get-metadata-keys":277,"./modules/es7.reflect.get-own-metadata":280,"./modules/es7.reflect.get-own-metadata-keys":279,"./modules/es7.reflect.has-metadata":281,"./modules/es7.reflect.has-own-metadata":282,"./modules/es7.reflect.metadata":283,"./modules/es7.set.to-json":284,"./modules/es7.string.at":285,"./modules/es7.string.match-all":286,"./modules/es7.string.pad-end":287,"./modules/es7.string.pad-start":288,"./modules/es7.string.trim-left":289,"./modules/es7.string.trim-right":290,"./modules/es7.symbol.async-iterator":291,"./modules/es7.symbol.observable":292,"./modules/es7.system.global":293,"./modules/web.dom.iterable":294,"./modules/web.immediate":295,"./modules/web.timers":296}],298:[function(require,module,exports){ (function () { 'use strict'; var ShimDOMException; var phases = { NONE: 0, CAPTURING_PHASE: 1, AT_TARGET: 2, BUBBLING_PHASE: 3 }; if (typeof DOMException === 'undefined') { // Todo: Better polyfill (if even needed here) ShimDOMException = function DOMException (msg, name) { // No need for `toString` as same as for `Error` var err = new Error(msg); err.name = name; return err; }; } else { ShimDOMException = DOMException; } var ev = new WeakMap(); var evCfg = new WeakMap(); // Todo: Set _ev argument outside of this function /** * We use an adapter class rather than a proxy not only for compatibility but also since we have to clone * native event properties anyways in order to properly set `target`, etc. * @note The regular DOM method `dispatchEvent` won't work with this polyfill as it expects a native event */ var ShimEvent = function Event (type) { // eslint-disable-line no-native-reassign // For WebIDL checks of function's `length`, we check `arguments` for the optional arguments this[Symbol.toStringTag] = 'Event'; this.toString = function () { return '[object Event]'; }; var evInit = arguments[1]; var _ev = arguments[2]; if (!arguments.length) { throw new TypeError("Failed to construct 'Event': 1 argument required, but only 0 present."); } evInit = evInit || {}; _ev = _ev || {}; var _evCfg = {}; if ('composed' in evInit) { _evCfg.composed = evInit.composed; } // _evCfg.isTrusted = true; // We are not always using this for user-created events // _evCfg.timeStamp = new Date().valueOf(); // This is no longer a timestamp, but monotonic (elapsed?) ev.set(this, _ev); evCfg.set(this, _evCfg); this.initEvent(type, evInit.bubbles, evInit.cancelable); Object.defineProperties(this, ['target', 'currentTarget', 'eventPhase', 'defaultPrevented'].reduce(function (obj, prop) { obj[prop] = { get: function () { return (/* prop in _evCfg && */ _evCfg[prop] !== undefined) ? _evCfg[prop] : ( prop in _ev ? _ev[prop] : ( // Defaults prop === 'eventPhase' ? 0 : (prop === 'defaultPrevented' ? false : null) ) ); } }; return obj; }, {}) ); var props = [ // Event 'type', 'bubbles', 'cancelable', // Defaults to false 'isTrusted', 'timeStamp', 'initEvent', // Other event properties (not used by our code) 'composedPath', 'composed' ]; if (this.toString() === '[object CustomEvent]') { props.push('detail', 'initCustomEvent'); } Object.defineProperties(this, props.reduce(function (obj, prop) { obj[prop] = { get: function () { return prop in _evCfg ? _evCfg[prop] : (prop in _ev ? _ev[prop] : ( ['bubbles', 'cancelable', 'composed'].indexOf(prop) > -1 ? false : undefined )); } }; return obj; }, {})); }; ShimEvent.prototype.preventDefault = function () { if (!(this instanceof ShimEvent)) { throw new TypeError('Illegal invocation'); } var _ev = ev.get(this); var _evCfg = evCfg.get(this); if (this.cancelable && !_evCfg._passive) { _evCfg.defaultPrevented = true; if (typeof _ev.preventDefault === 'function') { // Prevent any predefined defaults _ev.preventDefault(); } }; }; ShimEvent.prototype.stopImmediatePropagation = function () { var _evCfg = evCfg.get(this); _evCfg._stopImmediatePropagation = true; }; ShimEvent.prototype.stopPropagation = function () { var _evCfg = evCfg.get(this); _evCfg._stopPropagation = true; }; ShimEvent.prototype.initEvent = function (type, bubbles, cancelable) { // Chrome currently has function length 1 only but WebIDL says 3 // var bubbles = arguments[1]; // var cancelable = arguments[2]; var _evCfg = evCfg.get(this); if (_evCfg._dispatched) { return; } _evCfg.type = type; if (bubbles !== undefined) { _evCfg.bubbles = bubbles; } if (cancelable !== undefined) { _evCfg.cancelable = cancelable; } }; ['type', 'target', 'currentTarget'].forEach(function (prop) { Object.defineProperty(ShimEvent.prototype, prop, { enumerable: true, configurable: true, get: function () { throw new TypeError('Illegal invocation'); } }); }); ['eventPhase', 'defaultPrevented', 'bubbles', 'cancelable', 'timeStamp'].forEach(function (prop) { Object.defineProperty(ShimEvent.prototype, prop, { enumerable: true, configurable: true, get: function () { throw new TypeError('Illegal invocation'); } }); }); ['NONE', 'CAPTURING_PHASE', 'AT_TARGET', 'BUBBLING_PHASE'].forEach(function (prop, i) { Object.defineProperty(ShimEvent, prop, { enumerable: true, writable: false, value: i }); Object.defineProperty(ShimEvent.prototype, prop, { writable: false, value: i }); }); ShimEvent[Symbol.toStringTag] = 'Function'; ShimEvent.prototype[Symbol.toStringTag] = 'EventPrototype'; Object.defineProperty(ShimEvent, 'prototype', { writable: false }); var ShimCustomEvent = function CustomEvent (type) { var evInit = arguments[1]; var _ev = arguments[2]; ShimEvent.call(this, type, evInit, _ev); this[Symbol.toStringTag] = 'CustomEvent'; this.toString = function () { return '[object CustomEvent]'; }; // var _evCfg = evCfg.get(this); evInit = evInit || {}; this.initCustomEvent(type, evInit.bubbles, evInit.cancelable, 'detail' in evInit ? evInit.detail : null); }; Object.defineProperty(ShimCustomEvent.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: ShimCustomEvent }); ShimCustomEvent.prototype.initCustomEvent = function (type, bubbles, cancelable, detail) { if (!(this instanceof ShimCustomEvent)) { throw new TypeError('Illegal invocation'); } var _evCfg = evCfg.get(this); ShimCustomEvent.call(this, type, {bubbles: bubbles, cancelable: cancelable, detail: detail}, arguments[4]); if (_evCfg._dispatched) { return; } if (detail !== undefined) { _evCfg.detail = detail; } Object.defineProperty(this, 'detail', { get: function () { return _evCfg.detail; } }); }; ShimCustomEvent[Symbol.toStringTag] = 'Function'; ShimCustomEvent.prototype[Symbol.toStringTag] = 'CustomEventPrototype'; Object.setPrototypeOf(ShimCustomEvent, ShimEvent); // TODO: IDL needs but reported as slow! Object.defineProperty(ShimCustomEvent.prototype, 'detail', { enumerable: true, configurable: true, get: function () { throw new TypeError('Illegal invocation'); } }); Object.setPrototypeOf(ShimCustomEvent.prototype, ShimEvent.prototype); // TODO: IDL needs but reported as slow! Object.defineProperty(ShimCustomEvent, 'prototype', { writable: false }); function copyEvent (ev) { if ('detail' in ev) { return new ShimCustomEvent(ev.type, {bubbles: ev.bubbles, cancelable: ev.cancelable, detail: ev.detail}, ev); } return new ShimEvent(ev.type, {bubbles: ev.bubbles, cancelable: ev.cancelable}, ev); } function getListenersOptions (listeners, type, options) { var listenersByType = listeners[type]; if (listenersByType === undefined) listeners[type] = listenersByType = []; options = typeof options === 'boolean' ? {capture: options} : (options || {}); var stringifiedOptions = JSON.stringify(options); var listenersByTypeOptions = listenersByType.filter(function (obj) { return stringifiedOptions === JSON.stringify(obj.options); }); return {listenersByTypeOptions: listenersByTypeOptions, options: options, listenersByType: listenersByType}; } var methods = { addListener: function addListener (listeners, listener, type, options) { var listenerOptions = getListenersOptions(listeners, type, options); var listenersByTypeOptions = listenerOptions.listenersByTypeOptions; options = listenerOptions.options; var listenersByType = listenerOptions.listenersByType; if (listenersByTypeOptions.some(function (l) { return l.listener === listener; })) return; listenersByType.push({listener: listener, options: options}); }, removeListener: function removeListener (listeners, listener, type, options) { var listenerOptions = getListenersOptions(listeners, type, options); var listenersByType = listenerOptions.listenersByType; var stringifiedOptions = JSON.stringify(listenerOptions.options); listenersByType.some(function (l, i) { if (l.listener === listener && stringifiedOptions === JSON.stringify(l.options)) { listenersByType.splice(i, 1); if (!listenersByType.length) delete listeners[type]; return true; } }); }, hasListener: function hasListener (listeners, listener, type, options) { var listenerOptions = getListenersOptions(listeners, type, options); var listenersByTypeOptions = listenerOptions.listenersByTypeOptions; return listenersByTypeOptions.some(function (l) { return l.listener === listener; }); } }; function EventTarget () { throw new TypeError('Illegal constructor'); } Object.assign(EventTarget.prototype, ['Early', '', 'Late', 'Default'].reduce(function (obj, listenerType) { ['add', 'remove', 'has'].forEach(function (method) { obj[method + listenerType + 'EventListener'] = function (type, listener) { var options = arguments[2]; // We keep the listener `length` as per WebIDL if (arguments.length < 2) throw new TypeError('2 or more arguments required'); if (typeof type !== 'string') throw new ShimDOMException('UNSPECIFIED_EVENT_TYPE_ERR', 'UNSPECIFIED_EVENT_TYPE_ERR'); // eslint-disable-line eqeqeq if (listener.handleEvent) { listener = listener.handleEvent.bind(listener); } var arrStr = '_' + listenerType.toLowerCase() + (listenerType === '' ? 'l' : 'L') + 'isteners'; if (!this[arrStr]) Object.defineProperty(this, arrStr, {value: {}}); return methods[method + 'Listener'](this[arrStr], listener, type, options); }; }); return obj; }, {})); Object.assign(EventTarget.prototype, { __setOptions: function (customOptions) { customOptions = customOptions || {}; // Todo: Make into event properties? this._defaultSync = customOptions.defaultSync; this._extraProperties = customOptions.extraProperties || []; if (customOptions.legacyOutputDidListenersThrowFlag) { // IndexedDB this._legacyOutputDidListenersThrowCheck = true; this._extraProperties.push('__legacyOutputDidListenersThrowError'); } }, dispatchEvent: function (ev) { return this._dispatchEvent(ev, true); }, _dispatchEvent: function (ev, setTarget) { var me = this; ['early', '', 'late', 'default'].forEach(function (listenerType) { var arrStr = '_' + listenerType + (listenerType === '' ? 'l' : 'L') + 'isteners'; if (!this[arrStr]) Object.defineProperty(this, arrStr, {value: {}}); }, this); var _evCfg = evCfg.get(ev); if (_evCfg && setTarget && _evCfg._dispatched) throw new ShimDOMException('The object is in an invalid state.', 'InvalidStateError'); var eventCopy; if (_evCfg) { eventCopy = ev; } else { eventCopy = copyEvent(ev); _evCfg = evCfg.get(eventCopy); _evCfg._dispatched = true; this._extraProperties.forEach(function (prop) { if (prop in ev) { eventCopy[prop] = ev[prop]; // Todo: Put internal to `ShimEvent`? } }); } var type = eventCopy.type; function finishEventDispatch () { _evCfg.eventPhase = phases.NONE; _evCfg.currentTarget = null; delete _evCfg._children; } function invokeDefaults () { // Ignore stopPropagation from defaults _evCfg._stopImmediatePropagation = undefined; _evCfg._stopPropagation = undefined; // We check here for whether we should invoke since may have changed since timeout (if late listener prevented default) if (!eventCopy.defaultPrevented || !_evCfg.cancelable) { // 2nd check should be redundant _evCfg.eventPhase = phases.AT_TARGET; // Temporarily set before we invoke default listeners eventCopy.target.invokeCurrentListeners(eventCopy.target._defaultListeners, eventCopy, type); } finishEventDispatch(); } function continueEventDispatch () { // Ignore stop propagation of user now _evCfg._stopImmediatePropagation = undefined; _evCfg._stopPropagation = undefined; if (!me._defaultSync) { setTimeout(invokeDefaults, 0); } else invokeDefaults(); _evCfg.eventPhase = phases.AT_TARGET; // Temporarily set before we invoke late listeners // Sync default might have stopped if (!_evCfg._stopPropagation) { _evCfg._stopImmediatePropagation = undefined; _evCfg._stopPropagation = undefined; // We could allow stopPropagation by only executing upon (_evCfg._stopPropagation) eventCopy.target.invokeCurrentListeners(eventCopy.target._lateListeners, eventCopy, type); } finishEventDispatch(); return !eventCopy.defaultPrevented; } if (setTarget) _evCfg.target = this; switch (eventCopy.eventPhase) { default: case phases.NONE: _evCfg.eventPhase = phases.AT_TARGET; // Temporarily set before we invoke early listeners this.invokeCurrentListeners(this._earlyListeners, eventCopy, type); if (!this.__getParent) { _evCfg.eventPhase = phases.AT_TARGET; return this._dispatchEvent(eventCopy, false); } var par = this; var root = this; while (par.__getParent && (par = par.__getParent()) !== null) { if (!_evCfg._children) { _evCfg._children = []; } _evCfg._children.push(root); root = par; } root._defaultSync = me._defaultSync; _evCfg.eventPhase = phases.CAPTURING_PHASE; return root._dispatchEvent(eventCopy, false); case phases.CAPTURING_PHASE: if (_evCfg._stopPropagation) { return continueEventDispatch(); } this.invokeCurrentListeners(this._listeners, eventCopy, type); var child = _evCfg._children && _evCfg._children.length && _evCfg._children.pop(); if (!child || child === eventCopy.target) { _evCfg.eventPhase = phases.AT_TARGET; } if (child) child._defaultSync = me._defaultSync; return (child || this)._dispatchEvent(eventCopy, false); case phases.AT_TARGET: if (_evCfg._stopPropagation) { return continueEventDispatch(); } this.invokeCurrentListeners(this._listeners, eventCopy, type, true); if (!_evCfg.bubbles) { return continueEventDispatch(); } _evCfg.eventPhase = phases.BUBBLING_PHASE; return this._dispatchEvent(eventCopy, false); case phases.BUBBLING_PHASE: if (_evCfg._stopPropagation) { return continueEventDispatch(); } var parent = this.__getParent && this.__getParent(); if (!parent) { return continueEventDispatch(); } parent.invokeCurrentListeners(parent._listeners, eventCopy, type, true); parent._defaultSync = me._defaultSync; return parent._dispatchEvent(eventCopy, false); } }, invokeCurrentListeners: function (listeners, eventCopy, type, checkOnListeners) { var _evCfg = evCfg.get(eventCopy); var me = this; _evCfg.currentTarget = this; var listOpts = getListenersOptions(listeners, type, {}); var listenersByType = listOpts.listenersByType.concat(); var dummyIPos = listenersByType.length ? 1 : 0; listenersByType.some(function (listenerObj, i) { var onListener = checkOnListeners ? me['on' + type] : null; if (_evCfg._stopImmediatePropagation) return true; if (i === dummyIPos && typeof onListener === 'function') { // We don't splice this in as could be overwritten; executes here per // https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-attributes:event-handlers-14 this.tryCatch(eventCopy, function () { var ret = onListener.call(eventCopy.currentTarget, eventCopy); if (ret === false) { eventCopy.preventDefault(); } }); } var options = listenerObj.options; var once = options.once; // Remove listener after invoking once var passive = options.passive; // Don't allow `preventDefault` var capture = options.capture; // Use `_children` and set `eventPhase` _evCfg._passive = passive; if ((capture && eventCopy.target !== eventCopy.currentTarget && eventCopy.eventPhase === phases.CAPTURING_PHASE) || (eventCopy.eventPhase === phases.AT_TARGET || (!capture && eventCopy.target !== eventCopy.currentTarget && eventCopy.eventPhase === phases.BUBBLING_PHASE)) ) { var listener = listenerObj.listener; this.tryCatch(eventCopy, function () { listener.call(eventCopy.currentTarget, eventCopy); }); if (once) { this.removeEventListener(type, listener, options); } } }, this); this.tryCatch(eventCopy, function () { var onListener = checkOnListeners ? me['on' + type] : null; if (typeof onListener === 'function' && listenersByType.length < 2) { var ret = onListener.call(eventCopy.currentTarget, eventCopy); // Won't have executed if too short if (ret === false) { eventCopy.preventDefault(); } } }); return !eventCopy.defaultPrevented; }, tryCatch: function (ev, cb) { try { // Per MDN: Exceptions thrown by event handlers are reported // as uncaught exceptions; the event handlers run on a nested // callstack: they block the caller until they complete, but // exceptions do not propagate to the caller. cb(); } catch (err) { this.triggerErrorEvent(err, ev); } }, triggerErrorEvent: function (err, ev) { var error = err; if (typeof err === 'string') { error = new Error('Uncaught exception: ' + err); } var triggerGlobalErrorEvent; var useNodeImpl = false; if (typeof window === 'undefined' || typeof ErrorEvent === 'undefined' || ( window && typeof window === 'object' && !window.dispatchEvent) ) { useNodeImpl = true; triggerGlobalErrorEvent = function () { setTimeout(function () { // Node won't be able to catch in this way if we throw in the main thread // console.log(err); // Should we auto-log for user? throw error; // Let user listen to `process.on('uncaughtException', function(err) {});` }); }; } else { triggerGlobalErrorEvent = function () { // See https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror // and https://github.com/w3c/IndexedDB/issues/49 // Note that a regular Event will properly trigger // `window.addEventListener('error')` handlers, but it will not trigger // `window.onerror` as per https://html.spec.whatwg.org/multipage/webappapis.html#handler-onerror // Note also that the following line won't handle `window.addEventListener` handlers // if (window.onerror) window.onerror(error.message, err.fileName, err.lineNumber, error.columnNumber, error); // `ErrorEvent` properly triggers `window.onerror` and `window.addEventListener('error')` handlers var errEv = new ErrorEvent('error', { error: err, message: error.message || '', // We can't get the actually useful user's values! filename: error.fileName || '', lineno: error.lineNumber || 0, colno: error.columnNumber || 0 }); window.dispatchEvent(errEv); // console.log(err); // Should we auto-log for user? }; } // Todo: This really should always run here but as we can't set the global // `window` (e.g., using jsdom) since `setGlobalVars` becomes unable to // shim `indexedDB` in such a case currently (apparently due to // <https://github.com/axemclion/IndexedDBShim/issues/280>), we can't // avoid the above Node implementation (which, while providing some // fallback mechanism, is unstable) if (!useNodeImpl || !this._legacyOutputDidListenersThrowCheck) triggerGlobalErrorEvent(); // See https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke and // https://github.com/w3c/IndexedDB/issues/140 (also https://github.com/w3c/IndexedDB/issues/49 ) if (this._legacyOutputDidListenersThrowCheck) { ev.__legacyOutputDidListenersThrowError = error; } } }); EventTarget.prototype[Symbol.toStringTag] = 'EventTargetPrototype'; Object.defineProperty(EventTarget, 'prototype', { writable: false }); var ShimEventTarget = EventTarget; var EventTargetFactory = { createInstance: function (customOptions) { function EventTarget () { this.__setOptions(customOptions); } EventTarget.prototype = ShimEventTarget.prototype; return new EventTarget(); } }; EventTarget.ShimEvent = ShimEvent; EventTarget.ShimCustomEvent = ShimCustomEvent; EventTarget.ShimDOMException = ShimDOMException; EventTarget.ShimEventTarget = EventTarget; EventTarget.EventTargetFactory = EventTargetFactory; // Todo: Move to own library (but allowing WeakMaps to be passed in for sharing here) var exportObj = (typeof module !== 'undefined' && module.exports) ? exports : window; exportObj.ShimEvent = ShimEvent; exportObj.ShimCustomEvent = ShimCustomEvent; exportObj.ShimDOMException = ShimDOMException; exportObj.ShimEventTarget = EventTarget; exportObj.EventTargetFactory = EventTargetFactory; }()); },{}],299:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = exports.isAbsolute(path), trailingSlash = substr(path, -1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.isAbsolute = function(path) { return path.charAt(0) === '/'; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function(p, index) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); }; // path.relative(from, to) // posix version exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; exports.delimiter = ':'; exports.dirname = function(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; exports.basename = function(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPath(path)[3]; }; function filter (xs, f) { if (xs.filter) return xs.filter(f); var res = []; for (var i = 0; i < xs.length; i++) { if (f(xs[i], i, xs)) res.push(xs[i]); } return res; } // String.prototype.substr - negative index don't work in IE8 var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) { return str.substr(start, len) } : function (str, start, len) { if (start < 0) start = str.length + start; return str.substr(start, len); } ; }).call(this,require('_process')) },{"_process":300}],300:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],301:[function(require,module,exports){ (function (process,global){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ !(function(global) { "use strict"; var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } runtime.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. runtime.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return Promise.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return Promise.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. result.value = unwrapped; resolve(result); }, reject); } } if (typeof process === "object" && process.domain) { invoke = process.domain.bind(invoke); } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new Promise(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); runtime.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. runtime.async = function(innerFn, outerFn, self, tryLocsList) { var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList) ); return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { if (delegate.iterator.return) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[toStringTagSymbol] = "Generator"; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } runtime.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined; } return ContinueSentinel; } }; })( // Among the various tricks for obtaining a reference to the global // object, this seems to be the most reliable technique that does not // use indirect eval (which violates Content Security Policy). typeof global === "object" ? global : typeof window === "object" ? window : typeof self === "object" ? self : this ); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":300}],302:[function(require,module,exports){ // Since [immediate](https://github.com/calvinmetcalf/immediate) is // not doing the trick for our WebSQL transactions (at least in Node), // we are forced to make the promises run fully synchronously. function isPromise(p) { return p && typeof p.then === 'function'; } function addReject(prom, reject) { prom.then(null, reject) // Use this style for sake of non-Promise thenables (e.g., jQuery Deferred) } // States var PENDING = 2, FULFILLED = 0, // We later abuse these as array indices REJECTED = 1; function SyncPromise(fn) { var self = this; self.v = 0; // Value, this will be set to either a resolved value or rejected reason self.s = PENDING; // State of the promise self.c = [[],[]]; // Callbacks c[0] is fulfillment and c[1] contains rejection callbacks function transist(val, state) { self.v = val; self.s = state; self.c[state].forEach(function(fn) { fn(val); }); // Release memory, but if no handlers have been added, as we // assume that we will resolve/reject (truly) synchronously // and thus we avoid flagging checks about whether we've // already resolved/rejected. if (self.c[state].length) self.c = null; } function resolve(val) { if (!self.c) { // Already resolved (or will be resolved), do nothing. } else if (isPromise(val)) { addReject(val.then(resolve), reject); } else { transist(val, FULFILLED); } } function reject(reason) { if (!self.c) { // Already resolved (or will be resolved), do nothing. } else if (isPromise(reason)) { addReject(reason.then(reject), reject); } else { transist(reason, REJECTED); } } try { fn(resolve, reject); } catch (err) { reject(err); } } var prot = SyncPromise.prototype; prot.then = function(cb, errBack) { var self = this; return new SyncPromise(function(resolve, reject) { var rej = typeof errBack === 'function' ? errBack : reject; function settle() { try { resolve(cb ? cb(self.v) : self.v); } catch(e) { rej(e); } } if (self.s === FULFILLED) { settle(); } else if (self.s === REJECTED) { rej(self.v); } else { self.c[FULFILLED].push(settle); self.c[REJECTED].push(rej); } }); }; prot.catch = function(cb) { var self = this; return new SyncPromise(function(resolve, reject) { function settle() { try { resolve(cb(self.v)); } catch(e) { reject(e); } } if (self.s === REJECTED) { settle(); } else if (self.s === FULFILLED) { resolve(self.v); } else { self.c[REJECTED].push(settle); self.c[FULFILLED].push(resolve); } }); }; SyncPromise.all = function(promises) { return new SyncPromise(function(resolve, reject, l) { l = promises.length; var hasPromises = false; var newPromises = []; if (!l) { resolve(newPromises); return; } promises.forEach(function(p, i) { if (isPromise(p)) { addReject(p.then(function(res) { newPromises[i] = res; --l || resolve(newPromises); }), reject); } else { newPromises[i] = p; --l || resolve(promises); } }); }); }; SyncPromise.race = function(promises) { var resolved = false; return new SyncPromise(function(resolve, reject) { promises.some(function(p, i) { if (isPromise(p)) { addReject(p.then(function(res) { if (resolved) { return; } resolve(res); resolved = true; }), reject); } else { resolve(p); resolved = true; return true; } }); }); }; SyncPromise.resolve = function(val) { return new SyncPromise(function(resolve, reject) { resolve(val); }); }; SyncPromise.reject = function(val) { return new SyncPromise(function(resolve, reject) { reject(val); }); }; module.exports = SyncPromise; },{}],303:[function(require,module,exports){ module.exports = [ { sparseArrays: { testPlainObjects: true, test: function (x) {return Array.isArray(x);}, replace: function (a, stateObj) { stateObj.iterateUnsetNumeric = true; return a; } } }, { sparseUndefined: { test: function (x, stateObj) { return typeof x === 'undefined' && stateObj.ownKeys === false; }, replace: function (n) { return null; }, revive: function (s) { return undefined;} // Will avoid adding anything } } ]; },{}],304:[function(require,module,exports){ module.exports = require('./structured-cloning').concat({checkDataCloneException: [function (val) { // Should also throw with: // 1. `IsDetachedBuffer` (a process not called within the ECMAScript spec) // 2. `IsCallable` (covered by `typeof === 'function'` or a function's `toStringTag`) // 3. internal slots besides [[Prototype]] or [[Extensible]] (e.g., [[PromiseState]] or [[WeakMapData]]) // 4. exotic object (e.g., `Proxy`) (which does not have default behavior for one or more of the // essential internal methods that are limited to the following for non-function objects (we auto-exclude functions): // [[GetPrototypeOf]],[[SetPrototypeOf]],[[IsExtensible]],[[PreventExtensions]],[[GetOwnProperty]], // [[DefineOwnProperty]],[[HasProperty]],[[Get]],[[Set]],[[Delete]],[[OwnPropertyKeys]]); // except for the standard, built-in exotic objects, we'd need to know whether these methods had distinct behaviors // Note: There is no apparent way for us to detect a `Proxy` and reject (Chrome at least is not rejecting anyways) var stringTag = ({}.toString.call(val).slice(8, -1)); if ([ 'symbol', // Symbol's `toStringTag` is only "Symbol" for its initial value, so we check `typeof` 'function' // All functions including bound function exotic objects ].includes(typeof val) || [ 'Arguments', // A non-array exotic object 'Module', // A non-array exotic object 'Error', // `Error` and other errors have the [[ErrorData]] internal slot and give "Error" 'Promise', // Promise instances have an extra slot ([[PromiseState]]) but not throwing in Chrome `postMessage` 'WeakMap', // WeakMap instances have an extra slot ([[WeakMapData]]) but not throwing in Chrome `postMessage` 'WeakSet' // WeakSet instances have an extra slot ([[WeakSetData]]) but not throwing in Chrome `postMessage` ].includes(stringTag) || val === Object.prototype || // A non-array exotic object but not throwing in Chrome `postMessage` ((stringTag === 'Blob' || stringTag === 'File') && val.isClosed) || (val && typeof val === 'object' && typeof val.nodeType === 'number' && typeof val.insertBefore === 'function') // Duck-type DOM node objects (non-array exotic? objects which cannot be cloned by the SCA) ) { throw new DOMException('The object cannot be cloned.', 'DataCloneError'); } return false; }]}); },{"./structured-cloning":305}],305:[function(require,module,exports){ /* This preset includes types for the Structured Cloning Algorithm. */ module.exports = [ // Todo: Might also register `ImageBitmap` and synchronous `Blob`/`File`/`FileList` // ES5 require('../types/user-object'), // Processed last require('../presets/undefined'), require('../types/primitive-objects'), require('../types/special-numbers'), require('../types/date'), require('../types/regexp'), // ES2015 (ES6) typeof Map === 'function' && require('../types/map'), typeof Set === 'function' && require('../types/set'), typeof ArrayBuffer === 'function' && require('../types/arraybuffer'), typeof Uint8Array === 'function' && require('../types/typed-arrays'), typeof DataView === 'function' && require('../types/dataview'), typeof Intl !== 'undefined' && require('../types/intl-types'), // Non-built-ins require('../types/imagedata'), require('../types/imagebitmap'), // Async return require('../types/file'), require('../types/filelist'), require('../types/blob') ]; },{"../presets/undefined":306,"../types/arraybuffer":307,"../types/blob":308,"../types/dataview":309,"../types/date":310,"../types/file":311,"../types/filelist":312,"../types/imagebitmap":313,"../types/imagedata":314,"../types/intl-types":315,"../types/map":316,"../types/primitive-objects":317,"../types/regexp":318,"../types/set":319,"../types/special-numbers":320,"../types/typed-arrays":321,"../types/user-object":323}],306:[function(require,module,exports){ module.exports = [ require('../presets/sparse-undefined'), require('../types/undefined') ]; },{"../presets/sparse-undefined":303,"../types/undefined":322}],307:[function(require,module,exports){ var Typeson = require('typeson'); var B64 = require ('base64-arraybuffer'); exports.ArrayBuffer = [ function test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer';}, function encapsulate (b) { return B64.encode(b); }, function revive (b64) { return B64.decode(b64); } ]; // See also typed-arrays! },{"base64-arraybuffer":2,"typeson":325}],308:[function(require,module,exports){ var Typeson = require('typeson'); exports.Blob = { test: function (x) { return Typeson.toStringTag(x) === 'Blob'; }, replace: function encapsulate (b) { // Sync var req = new XMLHttpRequest(); req.open('GET', URL.createObjectURL(b), false); // Sync if (req.status !== 200 && req.status !== 0) throw new Error('Bad Blob access: ' + req.status); req.send(); return { type: b.type, stringContents: req.responseText }; }, revive: function (o) {return new Blob([o.stringContents], { type: o.type });}, replaceAsync: function encapsulateAsync (b) { return new Typeson.Promise(function (resolve, reject) { if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob reject(new Error('The Blob is closed')); return; } var reader = new FileReader(); reader.addEventListener('load', function () { resolve({ type: b.type, stringContents: reader.result }); }); reader.addEventListener('error', function () { reject(reader.error); }); reader.readAsText(b); }); } }; },{"typeson":325}],309:[function(require,module,exports){ var Typeson = require('typeson'); var B64 = require ('base64-arraybuffer'); exports.DataView = [ function (x) { return Typeson.toStringTag(x) === 'DataView'; }, function (dw) { return { buffer: B64.encode(dw.buffer), byteOffset: dw.byteOffset, byteLength: dw.byteLength }; }, function (obj) { return new DataView(B64.decode(obj.buffer), obj.byteOffset, obj.byteLength); } ]; },{"base64-arraybuffer":2,"typeson":325}],310:[function(require,module,exports){ var Typeson = require('typeson'); exports.Date = [ function (x) { return Typeson.toStringTag(x) === 'Date'; }, function (date) { return date.getTime(); }, function (time) { return new Date(time); } ]; },{"typeson":325}],311:[function(require,module,exports){ var Typeson = require('typeson'); exports.File = { test: function (x) { return Typeson.toStringTag(x) === 'File'; }, replace: function encapsulate (f) { // Sync var req = new XMLHttpRequest(); req.open('GET', URL.createObjectURL(f), false); // Sync if (req.status !== 200 && req.status !== 0) throw new Error('Bad Blob access: ' + req.status); req.send(); return { type: f.type, stringContents: req.responseText, name: f.name, lastModified: f.lastModified }; }, revive: function (o) {return new File([o.stringContents], o.name, { type: o.type, lastModified: o.lastModified });}, replaceAsync: function encapsulateAsync (f) { return new Typeson.Promise(function (resolve, reject) { if (f.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob reject(new Error('The File is closed')); return; } var reader = new FileReader(); reader.addEventListener('load', function () { resolve({ type: f.type, stringContents: reader.result, name: f.name, lastModified: f.lastModified }); }); reader.addEventListener('error', function () { reject(reader.error); }); reader.readAsText(f); }); } }; },{"typeson":325}],312:[function(require,module,exports){ var Typeson = require('typeson'); exports.File = require('./file').File; exports.FileList = { test: function (x) { return Typeson.toStringTag(x) === 'FileList'; }, replace: function (fl) { var arr = []; for (var i = 0; i < fl.length; i++) { arr[i] = fl.item(i); } return arr; }, revive: function (o) { function FileList () { this._files = arguments[0]; this.length = this._files.length; } FileList.prototype.item = function (index) { return this._files[index]; }; FileList.prototype[Symbol.toStringTag] = 'FileList'; return new FileList(o); } }; },{"./file":311,"typeson":325}],313:[function(require,module,exports){ /** ImageBitmap is browser / DOM specific. It also can only work same-domain (or CORS) */ var Typeson = require('typeson'); exports.ImageBitmap = { test: function (x) { return Typeson.toStringTag(x) === 'ImageBitmap'; }, replace: function (bm) { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); ctx.drawImage(bm, 0, 0); // Although `width` and `height` are part of `ImageBitMap`, these will // be auto-created for us when reviving with the data URL (and they are // not settable even if they weren't) // return {width: bm.width, height: bm.height, dataURL: canvas.toDataURL()}; return canvas.toDataURL(); }, revive: function (o) { /* var req = new XMLHttpRequest(); req.open('GET', o, false); // Sync if (req.status !== 200 && req.status !== 0) throw new Error('Bad ImageBitmap access: ' + req.status); req.send(); return req.responseText; */ var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var img = document.createElement('img'); // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577 img.onload = function () { ctx.drawImage(img, 0, 0); }; img.src = o; return canvas; // Works in contexts allowing an ImageBitmap (We might use `OffscreenCanvas.transferToBitmap` when supported) }, reviveAsync: function reviveAsync (o) { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var img = document.createElement('img'); // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577 img.onload = function () { ctx.drawImage(img, 0, 0); }; img.src = o; // o.dataURL; return createImageBitmap(canvas); // Returns a promise } }; },{"typeson":325}],314:[function(require,module,exports){ /** ImageData is browser / DOM specific (though `node-canvas` has it available on `Canvas`). */ var Typeson = require('typeson'); exports.ImageData = [ function (x) { return Typeson.toStringTag(x) === 'ImageData'; }, function (d) { return { array: Array.from(d.data), // Ensure `length` gets preserved for revival width: d.width, height: d.height }; }, function (o) {return new ImageData(new Uint8ClampedArray(o.array), o.width, o.height);} ]; },{"typeson":325}],315:[function(require,module,exports){ var Typeson = require('typeson'); exports["Intl.Collator"] = [ function (x) { return Typeson.hasConstructorOf(x, Intl.Collator); }, function (c) { return c.resolvedOptions(); }, function (options) { return new Intl.Collator(options.locale, options); } ]; exports["Intl.DateTimeFormat"] = [ function (x) { return Typeson.hasConstructorOf(x, Intl.DateTimeFormat); }, function (dtf) { return dtf.resolvedOptions(); }, function (options) { return new Intl.DateTimeFormat(options.locale, options); } ]; exports["Intl.NumberFormat"] = [ function (x) { return Typeson.hasConstructorOf(x, Intl.NumberFormat); }, function (nf) { return nf.resolvedOptions(); }, function (options) { return new Intl.NumberFormat(options.locale, options); } ]; },{"typeson":325}],316:[function(require,module,exports){ var Typeson = require('typeson'); var makeArray = require('../utils/array-from-iterator'); exports.Map = [ function (x) { return Typeson.toStringTag(x) === 'Map'; }, function (map) { return makeArray(map.entries()); }, function (entries) { return new Map(entries); } ]; },{"../utils/array-from-iterator":324,"typeson":325}],317:[function(require,module,exports){ // This module is for objectified primitives (such as new Number(3) or // new String("foo")) var Typeson = require('typeson'); module.exports = { // String Object (not primitive string which need no type spec) StringObject: [ function (x) { return Typeson.toStringTag(x) === 'String' && typeof x === 'object'; }, function (s) { return String(s); }, // convert to primitive string function (s) { return new String(s); } // Revive to an objectified string ], // Boolean Object (not primitive boolean which need no type spec) BooleanObject: [ function (x) { return Typeson.toStringTag(x) === 'Boolean' && typeof x === 'object'; }, function (b) { return Boolean(b); }, // convert to primitive boolean function (b) { return new Boolean(b); } // Revive to an objectified Boolean ], // Number Object (not primitive number which need no type spec) NumberObject: [ function (x) { return Typeson.toStringTag(x) === 'Number' && typeof x === 'object'; }, function (n) { return Number(n); }, // convert to primitive number function (n) { return new Number(n); } // Revive to an objectified number ] }; },{"typeson":325}],318:[function(require,module,exports){ var Typeson = require('typeson'); exports.RegExp = [ function (x) { return Typeson.toStringTag(x) === 'RegExp'; }, function (rexp) { return { source: rexp.source, flags: (rexp.global?'g':'')+(rexp.ignoreCase?'i':'')+(rexp.multiline?'m':'')+(rexp.sticky?'y':'')+(rexp.unicode?'u':'') }; }, function (data) { return new RegExp (data.source, data.flags); } ]; },{"typeson":325}],319:[function(require,module,exports){ var Typeson = require('typeson'); var makeArray = require('../utils/array-from-iterator'); exports.Set = [ function (x) { return Typeson.toStringTag(x) === 'Set'; }, function (set) { return makeArray(set.values()); }, function (values) { return new Set(values); } ]; },{"../utils/array-from-iterator":324,"typeson":325}],320:[function(require,module,exports){ exports.SpecialNumber = [ function (x) { return typeof x === 'number' && (isNaN(x) || x === Infinity || x === -Infinity); }, function (n) { return isNaN(n) ? "NaN" : n > 0 ? "Infinity" : "-Infinity" }, function (s) { return {NaN: NaN, Infinity: Infinity, "-Infinity": -Infinity}[s];} ]; },{}],321:[function(require,module,exports){ (function (global){ var Typeson = require('typeson'); var B64 = require ('base64-arraybuffer'); var _global = typeof self === 'undefined' ? global : self; [ "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array" ].forEach(function (typeName) { var TypedArray = _global[typeName]; if (TypedArray) exports[typeName] = [ function test (x) { return Typeson.toStringTag(x) === typeName; }, function encapsulate (a) { return B64.encode (a.buffer, a.byteOffset, a.byteLength); }, function revive (b64) { return new TypedArray (B64.decode(b64)); } ]; }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"base64-arraybuffer":2,"typeson":325}],322:[function(require,module,exports){ // This does not preserve `undefined` in sparse arrays; see the `undefined` or `sparse-undefined` preset var Typeson = require('typeson'); module.exports = { undefined: [ function (x, stateObj) { return typeof x === 'undefined' && (stateObj.ownKeys || !('ownKeys' in stateObj)); }, function (n) { return null; }, function (s) { return new Typeson.Undefined();} // Will add `undefined` (returning `undefined` would instead avoid explicitly setting) ] }; },{"typeson":325}],323:[function(require,module,exports){ var Typeson = require('typeson'); exports.userObjects = [ function (x, stateObj) { return Typeson.isUserObject(x); }, function (n) { return Object.assign({}, n); }, function (s) { return s;} ]; },{"typeson":325}],324:[function(require,module,exports){ module.exports = Array.from || function (iterator) { var res = []; for (var i=iterator.next(); !i.done; i = iterator.next()) { res.push(i.value); } return res; } },{}],325:[function(require,module,exports){ var keys = Object.keys, isArray = Array.isArray, toString = ({}.toString), getProto = Object.getPrototypeOf, hasOwn = ({}.hasOwnProperty), fnToString = hasOwn.toString; function isThenable (v, catchCheck) { return Typeson.isObject(v) && typeof v.then === 'function' && (!catchCheck || typeof v.catch === 'function'); } function toStringTag (val) { return toString.call(val).slice(8, -1); } function hasConstructorOf (a, b) { if (!a || typeof a !== 'object') { return false; } var proto = getProto(a); if (!proto) { return false; } var Ctor = hasOwn.call(proto, 'constructor') && proto.constructor; if (typeof Ctor !== 'function') { return b === null; } return typeof Ctor === 'function' && b !== null && fnToString.call(Ctor) === fnToString.call(b); } function isPlainObject (val) { // Mirrors jQuery's if (!val || toStringTag(val) !== 'Object') { return false; } var proto = getProto(val); if (!proto) { // `Object.create(null)` return true; } return hasConstructorOf(val, Object); } function isUserObject (val) { if (!val || toStringTag(val) !== 'Object') { return false; } var proto = getProto(val); if (!proto) { // `Object.create(null)` return true; } return hasConstructorOf(val, Object) || isUserObject(proto); } function isObject (v) { return v && typeof v === 'object' } /* Typeson - JSON with types * License: The MIT License (MIT) * Copyright (c) 2016 David Fahlander */ /** An instance of this class can be used to call stringify() and parse(). * Typeson resolves cyclic references by default. Can also be extended to * support custom types using the register() method. * * @constructor * @param {{cyclic: boolean}} [options] - if cyclic (default true), cyclic references will be handled gracefully. */ function Typeson (options) { // Replacers signature: replace (value). Returns falsy if not replacing. Otherwise ['Date', value.getTime()] var plainObjectReplacers = []; var nonplainObjectReplacers = []; // Revivers: map {type => reviver}. Sample: {'Date': value => new Date(value)} var revivers = {}; /** Types registered via register() */ var regTypes = this.types = {}; /** Serialize given object to Typeson. * * Arguments works identical to those of JSON.stringify(). */ var stringify = this.stringify = function (obj, replacer, space, opts) { // replacer here has nothing to do with our replacers. opts = Object.assign({}, options, opts, {stringification: true}); var encapsulated = encapsulate(obj, null, opts); if (isArray(encapsulated)) { return JSON.stringify(encapsulated[0], replacer, space); } return encapsulated.then(function (res) { return JSON.stringify(res, replacer, space); }); }; // Also sync but throws on non-sync result this.stringifySync = function (obj, replacer, space, opts) { return stringify(obj, replacer, space, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true})); }; this.stringifyAsync = function (obj, replacer, space, opts) { return stringify(obj, replacer, space, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false})); }; /** Parse Typeson back into an obejct. * * Arguments works identical to those of JSON.parse(). */ var parse = this.parse = function (text, reviver, opts) { opts = Object.assign({}, options, opts, {parse: true}); return revive(JSON.parse(text, reviver), opts); // This reviver has nothing to do with our revivers. }; // Also sync but throws on non-sync result this.parseSync = function (text, reviver, opts) { return parse(text, reviver, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true})); // This reviver has nothing to do with our revivers. }; this.parseAsync = function (text, reviver, opts) { return parse(text, reviver, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false})); // This reviver has nothing to do with our revivers. }; /** Encapsulate a complex object into a plain Object by replacing registered types with * plain objects representing the types data. * * This method is used internally by Typeson.stringify(). * @param {Object} obj - Object to encapsulate. */ var encapsulate = this.encapsulate = function (obj, stateObj, opts) { opts = Object.assign({sync: true}, options, opts); var sync = opts.sync; var types = {}, refObjs = [], // For checking cyclic references refKeys = [], // For checking cyclic references promisesDataRoot = []; // Clone the object deeply while at the same time replacing any special types or cyclic reference: var cyclic = opts && ('cyclic' in opts) ? opts.cyclic : true; var ret = _encapsulate('', obj, cyclic, stateObj || {}, promisesDataRoot); function finish (ret) { // Add $types to result only if we ever bumped into a special type (or special case where object has own `$types`) if (keys(types).length) { if (!ret || !isPlainObject(ret) || // Special if array (or a primitive) was serialized because JSON would ignore custom `$types` prop on it ret.hasOwnProperty('$types') // Also need to handle if this is an object with its own `$types` property (to avoid ambiguity) ) ret = {$: ret, $types: {$: types}}; else ret.$types = types; } else if (isObject(ret) && ret.hasOwnProperty('$types')) { ret = {$: ret, $types: true}; } return ret; } function checkPromises (ret, promisesData) { return Promise.all( promisesData.map(function (pd) {return pd[1].p;}) ).then(function (promResults) { return Promise.all( promResults.map(function (promResult) { var newPromisesData = []; var prData = promisesData.splice(0, 1)[0]; // var [keypath, , cyclic, stateObj, parentObj, key] = prData; var keyPath = prData[0]; var cyclic = prData[2]; var stateObj = prData[3]; var parentObj = prData[4]; var key = prData[5]; var encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData); var isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); if (keyPath && isTypesonPromise) { // Handle case where an embedded custom type itself returns a `Typeson.Promise` return encaps.p.then(function (encaps2) { parentObj[key] = encaps2; return checkPromises(ret, newPromisesData); }); } if (keyPath) parentObj[key] = encaps; else if (isTypesonPromise) { ret = encaps.p; } else ret = encaps; // If this is itself a `Typeson.Promise` (because the original value supplied was a promise or because the supplied custom type value resolved to one), returning it below will be fine since a promise is expected anyways given current config (and if not a promise, it will be ready as the resolve value) return checkPromises(ret, newPromisesData); }) ); }).then(function () { return ret; }); }; return promisesDataRoot.length ? sync && opts.throwOnBadSyncType ? (function () { throw new TypeError("Sync method requested but async result obtained"); }()) : Promise.resolve(checkPromises(ret, promisesDataRoot)).then(finish) : !sync && opts.throwOnBadSyncType ? (function () { throw new TypeError("Async method requested but sync result obtained"); }()) : (opts.stringification && sync // If this is a synchronous request for stringification, yet a promise is the result, we don't want to resolve leading to an async result, so we return an array to avoid ambiguity ? [finish(ret)] : (sync ? finish(ret) : Promise.resolve(finish(ret)) )); function _encapsulate (keypath, value, cyclic, stateObj, promisesData) { var $typeof = typeof value; if ($typeof in {string: 1, boolean: 1, number: 1, undefined: 1 }) return value === undefined || ($typeof === 'number' && (isNaN(value) || value === -Infinity || value === Infinity)) ? replace(keypath, value, stateObj, promisesData) : value; if (value === null) return value; if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric) { // Options set to detect cyclic references and be able to rewrite them. var refIndex = refObjs.indexOf(value); if (refIndex < 0) { if (cyclic === true) { refObjs.push(value); refKeys.push(keypath); } } else { types[keypath] = '#'; return '#' + refKeys[refIndex]; } } var isPlainObj = isPlainObject(value); var isArr = isArray(value); var replaced = ( ((isPlainObj || isArr) && (!plainObjectReplacers.length || stateObj.replaced)) || stateObj.iterateIn // Running replace will cause infinite loop as will test positive again ) // Optimization: if plain object and no plain-object replacers, don't try finding a replacer ? value : replace(keypath, value, stateObj, promisesData, isPlainObj || isArr); if (replaced !== value) return replaced; var clone; if (isArr || stateObj.iterateIn === 'array') clone = new Array(value.length); else if (isPlainObj || stateObj.iterateIn === 'object') clone = {}; else if (keypath === '' && hasConstructorOf(value, TypesonPromise)) { promisesData.push([keypath, value, cyclic, stateObj]); return value; } else return value; // Only clone vanilla objects and arrays // Iterate object or array if (stateObj.iterateIn) { for (var key in value) { var ownKeysObj = {ownKeys: value.hasOwnProperty(key)}; var kp = keypath + (keypath ? '.' : '') + key; var val = _encapsulate(kp, value[key], !!cyclic, ownKeysObj, promisesData); if (hasConstructorOf(val, TypesonPromise)) { promisesData.push([kp, val, !!cyclic, ownKeysObj, clone, key]); } else if (val !== undefined) clone[key] = val; } } else { // Note: Non-indexes on arrays won't survive stringify so somewhat wasteful for arrays, but so too is iterating all numeric indexes on sparse arrays when not wanted or filtering own keys for positive integers keys(value).forEach(function (key) { var kp = keypath + (keypath ? '.' : '') + key; var val = _encapsulate(kp, value[key], !!cyclic, {ownKeys: true}, promisesData); if (hasConstructorOf(val, TypesonPromise)) { promisesData.push([kp, val, !!cyclic, {ownKeys: true}, clone, key]); } else if (val !== undefined) clone[key] = val; }); } // Iterate array for non-own numeric properties (we can't replace the prior loop though as it iterates non-integer keys) if (stateObj.iterateUnsetNumeric) { for (var i = 0, vl = value.length; i < vl; i++) { if (!(i in value)) { var kp = keypath + (keypath ? '.' : '') + i; var val = _encapsulate(kp, undefined, !!cyclic, {ownKeys: false}, promisesData); if (hasConstructorOf(val, TypesonPromise)) { promisesData.push([kp, val, !!cyclic, {ownKeys: false}, clone, i]); } else if (val !== undefined) clone[i] = val; } } } return clone; } function replace (key, value, stateObj, promisesData, plainObject) { // Encapsulate registered types var replacers = plainObject ? plainObjectReplacers : nonplainObjectReplacers; var i = replacers.length; while (i--) { if (replacers[i].test(value, stateObj)) { var type = replacers[i].type; if (revivers[type]) { // Record the type only if a corresponding reviver exists. // This is to support specs where only replacement is done. // For example ensuring deep cloning of the object, or // replacing a type to its equivalent without the need to revive it. var existing = types[key]; // type can comprise an array of types (see test shouldSupportIntermediateTypes) types[key] = existing ? [type].concat(existing) : type; } // Now, also traverse the result in case it contains it own types to replace stateObj = Object.assign(stateObj, {replaced: true}); if ((sync || !replacers[i].replaceAsync) && !replacers[i].replace) { return _encapsulate(key, value, cyclic && 'readonly', stateObj, promisesData); } var replaceMethod = sync || !replacers[i].replaceAsync ? 'replace' : 'replaceAsync'; return _encapsulate(key, replacers[i][replaceMethod](value, stateObj), cyclic && 'readonly', stateObj, promisesData); } } return value; } }; // Also sync but throws on non-sync result this.encapsulateSync = function (obj, stateObj, opts) { return encapsulate(obj, stateObj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true})); }; this.encapsulateAsync = function (obj, stateObj, opts) { return encapsulate(obj, stateObj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false})); }; /** Revive an encapsulated object. * This method is used internally by JSON.parse(). * @param {Object} obj - Object to revive. If it has $types member, the properties that are listed there * will be replaced with its true type instead of just plain objects. */ var revive = this.revive = function (obj, opts) { opts = Object.assign({sync: true}, options, opts); var sync = opts.sync; var types = obj && obj.$types, ignore$Types = true; if (!types) return obj; // No type info added. Revival not needed. if (types === true) return obj.$; // Object happened to have own `$types` property but with no actual types, so we unescape and return that object if (types.$ && isPlainObject(types.$)) { // Special when root object is not a trivial Object, it will be encapsulated in $. It will also be encapsulated in $ if it has its own `$` property to avoid ambiguity obj = obj.$; types = types.$; ignore$Types = false; } var keyPathResolutions = []; var ret = _revive('', obj, null, opts); ret = hasConstructorOf(ret, Undefined) ? undefined : ret; return isThenable(ret) ? sync && opts.throwOnBadSyncType ? (function () { throw new TypeError("Sync method requested but async result obtained"); }()) : ret : !sync && opts.throwOnBadSyncType ? (function () { throw new TypeError("Async method requested but sync result obtained"); }()) : sync ? ret : Promise.resolve(ret); function _revive (keypath, value, target, opts, clone, key) { if (ignore$Types && keypath === '$types') return; var type = types[keypath]; if (isArray(value) || isPlainObject(value)) { var clone = isArray(value) ? new Array(value.length) : {}; // Iterate object or array keys(value).forEach(function (key) { var val = _revive(keypath + (keypath ? '.' : '') + key, value[key], target || clone, opts, clone, key); if (hasConstructorOf(val, Undefined)) clone[key] = undefined; else if (val !== undefined) clone[key] = val; }); value = clone; while (keyPathResolutions.length) { // Try to resolve cyclic reference as soon as available var kpr = keyPathResolutions[0]; var target = kpr[0]; var keyPath = kpr[1]; var clone = kpr[2]; var key = kpr[3]; var val = getByKeyPath(target, keyPath); if (hasConstructorOf(val, Undefined)) clone[key] = undefined; else if (val !== undefined) clone[key] = val; else break; keyPathResolutions.splice(0, 1); } } if (!type) return value; if (type === '#') { var ret = getByKeyPath(target, value.substr(1)); if (ret === undefined) { // Cyclic reference not yet available keyPathResolutions.push([target, value.substr(1), clone, key]); } return ret; } var sync = opts.sync; return [].concat(type).reduce(function (val, type) { var reviver = revivers[type]; if (!reviver) throw new Error ('Unregistered type: ' + type); return reviver[ sync && reviver.revive ? 'revive' : !sync && reviver.reviveAsync ? 'reviveAsync' : 'revive' ](val); }, value); } }; // Also sync but throws on non-sync result this.reviveSync = function (obj, opts) { return revive(obj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: true})); }; this.reviveAsync = function (obj, opts) { return revive(obj, Object.assign({}, {throwOnBadSyncType: true}, opts, {sync: false})); }; /** Register types. * For examples how to use this method, see https://github.com/dfahlander/typeson-registry/tree/master/types * @param {Array.<Object.<string,Function[]>>} typeSpec - Types and their functions [test, encapsulate, revive]; */ this.register = function (typeSpecSets, opts) { opts = opts || {}; [].concat(typeSpecSets).forEach(function R (typeSpec) { if (isArray(typeSpec)) return typeSpec.map(R); // Allow arrays of arrays of arrays... typeSpec && keys(typeSpec).forEach(function (typeId) { if (typeId === '#') { throw new TypeError('# cannot be used as a type name as it is reserved for cyclic objects'); } var spec = typeSpec[typeId]; var replacers = spec.testPlainObjects ? plainObjectReplacers : nonplainObjectReplacers; var existingReplacer = replacers.filter(function(r){ return r.type === typeId; }); if (existingReplacer.length) { // Remove existing spec and replace with this one. replacers.splice(replacers.indexOf(existingReplacer[0]), 1); delete revivers[typeId]; delete regTypes[typeId]; } if (spec) { if (typeof spec === 'function') { // Support registering just a class without replacer/reviver var Class = spec; spec = { test: function (x) { return x.constructor === Class; }, replace: function (x) { return assign({}, x); }, revive: function (x) { return assign(Object.create(Class.prototype), x); } }; } else if (isArray(spec)) { spec = { test: spec[0], replace: spec[1], revive: spec[2] }; } var replacerObj = { type: typeId, test: spec.test.bind(spec) }; if (spec.replace) { replacerObj.replace = spec.replace.bind(spec); } if (spec.replaceAsync) { replacerObj.replaceAsync = spec.replaceAsync.bind(spec); } var start = typeof opts.fallback === 'number' ? opts.fallback : (opts.fallback ? 0 : Infinity); if (spec.testPlainObjects) { plainObjectReplacers.splice(start, 0, replacerObj); } else { nonplainObjectReplacers.splice(start, 0, replacerObj); } // Todo: We might consider a testAsync type if (spec.revive || spec.reviveAsync) { var reviverObj = {}; if (spec.revive) reviverObj.revive = spec.revive.bind(spec); if (spec.reviveAsync) reviverObj.reviveAsync = spec.reviveAsync.bind(spec); revivers[typeId] = reviverObj; } regTypes[typeId] = spec; // Record to be retrieved via public types property. } }); }); return this; }; } function assign(t,s) { keys(s).map(function (k) { t[k] = s[k]; }); return t; } /** getByKeyPath() utility */ function getByKeyPath (obj, keyPath) { if (keyPath === '') return obj; var period = keyPath.indexOf('.'); if (period !== -1) { var innerObj = obj[keyPath.substr(0, period)]; return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); } return obj[keyPath]; } function Undefined () {} // With ES6 classes, we may be able to simply use `class TypesonPromise extends Promise` and add a string tag for detection function TypesonPromise (f) { this.p = new Promise(f); }; TypesonPromise.prototype.then = function (onFulfilled, onRejected) { var that = this; return new TypesonPromise(function (typesonResolve, typesonReject) { that.p.then(function (res) { typesonResolve(onFulfilled ? onFulfilled(res) : res); }, function (r) { that.p['catch'](function (res) { return onRejected ? onRejected(res) : Promise.reject(res); }).then(typesonResolve, typesonReject); }); }); }; TypesonPromise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); }; TypesonPromise.resolve = function (v) { return new TypesonPromise(function (typesonResolve) { typesonResolve(v); }); }; TypesonPromise.reject = function (v) { return new TypesonPromise(function (typesonResolve, typesonReject) { typesonReject(v); }); }; ['all', 'race'].map(function (meth) { TypesonPromise[meth] = function (promArr) { return new TypesonPromise(function (typesonResolve, typesonReject) { Promise[meth](promArr.map(function (prom) {return prom.p;})).then(typesonResolve, typesonReject); }); }; }); // The following provide classes meant to avoid clashes with other values Typeson.Undefined = Undefined; // To insist `undefined` should be added Typeson.Promise = TypesonPromise; // To support async encapsulation/stringification // Some fundamental type-checking utilities Typeson.isThenable = isThenable; Typeson.toStringTag = toStringTag; Typeson.hasConstructorOf = hasConstructorOf; Typeson.isObject = isObject; Typeson.isPlainObject = isPlainObject; Typeson.isUserObject = isUserObject; module.exports = Typeson; },{}],326:[function(require,module,exports){ module.exports=/[\xC0-\xC5\xC7-\xCF\xD1-\xD6\xD9-\xDD\xE0-\xE5\xE7-\xEF\xF1-\xF6\xF9-\xFD\xFF-\u010F\u0112-\u0125\u0128-\u0130\u0134-\u0137\u0139-\u013E\u0143-\u0148\u014C-\u0151\u0154-\u0165\u0168-\u017E\u01A0\u01A1\u01AF\u01B0\u01CD-\u01DC\u01DE-\u01E3\u01E6-\u01F0\u01F4\u01F5\u01F8-\u021B\u021E\u021F\u0226-\u0233\u0344\u0385\u0386\u0388-\u038A\u038C\u038E-\u0390\u03AA-\u03B0\u03CA-\u03CE\u03D3\u03D4\u0400\u0401\u0403\u0407\u040C-\u040E\u0419\u0439\u0450\u0451\u0453\u0457\u045C-\u045E\u0476\u0477\u04C1\u04C2\u04D0-\u04D3\u04D6\u04D7\u04DA-\u04DF\u04E2-\u04E7\u04EA-\u04F5\u04F8\u04F9\u0622-\u0626\u06C0\u06C2\u06D3\u0929\u0931\u0934\u0958-\u095F\u09CB\u09CC\u09DC\u09DD\u09DF\u0A33\u0A36\u0A59-\u0A5B\u0A5E\u0B48\u0B4B\u0B4C\u0B5C\u0B5D\u0B94\u0BCA-\u0BCC\u0C48\u0CC0\u0CC7\u0CC8\u0CCA\u0CCB\u0D4A-\u0D4C\u0DDA\u0DDC-\u0DDE\u0F43\u0F4D\u0F52\u0F57\u0F5C\u0F69\u0F73\u0F75\u0F76\u0F78\u0F81\u0F93\u0F9D\u0FA2\u0FA7\u0FAC\u0FB9\u1026\u1B06\u1B08\u1B0A\u1B0C\u1B0E\u1B12\u1B3B\u1B3D\u1B40\u1B41\u1B43\u1E00-\u1E99\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FC1-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEE\u1FF2-\u1FF4\u1FF6-\u1FFC\u212B\u219A\u219B\u21AE\u21CD-\u21CF\u2204\u2209\u220C\u2224\u2226\u2241\u2244\u2247\u2249\u2260\u2262\u226D-\u2271\u2274\u2275\u2278\u2279\u2280\u2281\u2284\u2285\u2288\u2289\u22AC-\u22AF\u22E0-\u22E3\u22EA-\u22ED\u2ADC\u304C\u304E\u3050\u3052\u3054\u3056\u3058\u305A\u305C\u305E\u3060\u3062\u3065\u3067\u3069\u3070\u3071\u3073\u3074\u3076\u3077\u3079\u307A\u307C\u307D\u3094\u309E\u30AC\u30AE\u30B0\u30B2\u30B4\u30B6\u30B8\u30BA\u30BC\u30BE\u30C0\u30C2\u30C5\u30C7\u30C9\u30D0\u30D1\u30D3\u30D4\u30D6\u30D7\u30D9\u30DA\u30DC\u30DD\u30F4\u30F7-\u30FA\u30FE\uAC00-\uD7A3\uFB1D\uFB1F\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFB4E]|\uD804[\uDC9A\uDC9C\uDCAB\uDD2E\uDD2F\uDF4B\uDF4C]|\uD805[\uDCBB\uDCBC\uDCBE\uDDBA\uDDBB]|\uD834[\uDD5E-\uDD64\uDDBB-\uDDC0]/ },{}],327:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var map = {}; var CFG = {}; [ // Boolean for verbose reporting 'DEBUG', // Effectively defaults to false (ignored unless `true`) 'cacheDatabaseInstances', // Boolean (effectively defaults to true) on whether to cache WebSQL `openDatabase` instances 'autoName', // Boolean on whether to auto-name databases (based on an auto-increment) when // the empty string is supplied; useful with `memoryDatabase`; defaults to `false` // which means the empty string will be used as the (valid) database name // Determines whether the slow-performing `Object.setPrototypeOf` calls required // for full WebIDL compliance will be used. Probably only needed for testing // or environments where full introspection on class relationships is required; // see http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements 'fullIDLSupport', // Effectively defaults to false (ignored unless `true`) // Boolean on whether to perform origin checks in `IDBFactory` methods 'checkOrigin', // Effectively defaults to `true` (must be set to `false` to cancel checks) // Used by `IDBCursor` continue methods for number of records to cache; 'cursorPreloadPackSize', // Defaults to 100 // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`); // or just use the Unicode builds which invoke this method // automatically using the large, fully spec-compliant, regular // expression strings of `src/UnicodeIdentifiers.js`) 'UnicodeIDStart', // In the non-Unicode builds, defaults to /[$A-Z_a-z]/ 'UnicodeIDContinue', // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/ // -----------SQL CONFIG---------- // Object (`window` in the browser) on which there may be an // `openDatabase` method (if any) for WebSQL. (The browser // throws if attempting to call `openDatabase` without the window // so this is why the config doesn't just allow the function.) 'win', // Defaults to `window` or `self` in browser builds or // a singleton object with the `openDatabase` method set to // the "websql" package in Node. // For internal `openDatabase` calls made by `IDBFactory` methods; // per the WebSQL spec, "User agents are expected to use the display name // and the estimated database size to optimize the user experience. // For example, a user agent could use the estimated size to suggest an // initial quota to the user. This allows a site that is aware that it // will try to use hundreds of megabytes to declare this upfront, instead // of the user agent prompting the user for permission to increase the // quota every five megabytes." 'DEFAULT_DB_SIZE', // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari // NODE-IMPINGING SETTINGS (created for sake of limitations in Node or desktop file // system implementation but applied by default in browser for parity) // Used when setting global shims to determine whether to try to add // other globals shimmed by the library (`ShimDOMException`, `ShimDOMStringList`, // `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`) 'addNonIDBGlobals', // Effectively defaults to `false` (ignored unless `true`) // Used when setting global shims to determine whether to try to overwrite // other globals shimmed by the library (`DOMException`, `DOMStringList`, // `Event`, `CustomEvent`, `EventTarget`) 'replaceNonIDBGlobals', // Effectively defaults to `false` (ignored unless `true`) // Overcoming limitations with node-sqlite3/storing database name on file systems // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words 'escapeDatabaseName', // Defaults to prefixing database with `D_`, escaping // `databaseCharacterEscapeList`, escaping NUL, and // escaping upper case letters, as well as enforcing // `databaseNameLengthLimit` 'unescapeDatabaseName', // Not used internally; usable as a convenience method 'databaseCharacterEscapeList', // Defaults to global regex representing the following // (characters nevertheless commonly reserved in modern, Unicode-supporting // systems): 0x00-0x1F 0x7F " * / : < > ? \ | 'databaseNameLengthLimit', // Defaults to 254 (shortest typical modern file length limit) 'escapeNFDForDatabaseNames', // Boolean defaulting to true on whether to escape NFD-escaping // characters to avoid clashes on MacOS which performs NFD on files // Boolean on whether to add the `.sqlite` extension to file names; // defaults to `true` 'addSQLiteExtension', ['memoryDatabase', function (val) { // Various types of in-memory databases that can auto-delete if (!/^(?::memory:|file::memory:(\?[^#]*)?(#.*)?)?$/.test(val)) { throw new TypeError('`memoryDatabase` must be the empty string, ":memory:", or a "file::memory:[?queryString][#hash] URL".'); } }], // NODE-SPECIFIC CONFIG // Boolean on whether to delete the database file itself after `deleteDatabase`; // defaults to `true` as the database will be empty 'deleteDatabaseFiles', 'databaseBasePath', 'sysDatabaseBasePath', // NODE-SPECIFIC WEBSQL CONFIG 'sqlBusyTimeout', // Defaults to 1000 'sqlTrace', // Callback not used by default 'sqlProfile' // Callback not used by default ].forEach(function (prop) { var validator = void 0; if (Array.isArray(prop)) { validator = prop[1]; prop = prop[0]; } Object.defineProperty(CFG, prop, { get: function get() { return map[prop]; }, set: function set(val) { if (validator) { validator(val); } map[prop] = val; } }); }); exports.default = CFG; module.exports = exports['default']; },{}],328:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.webSQLErrback = exports.createDOMException = exports.ShimDOMException = exports.findError = exports.logError = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* globals DOMException */ var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Creates a native DOMException, for browsers that support it * @returns {DOMException} */ function createNativeDOMException(name, message) { return new DOMException.prototype.constructor(message, name || 'DOMException'); } var codes = { // From web-platform-tests testharness.js name_code_map (though not in new spec) IndexSizeError: 1, HierarchyRequestError: 3, WrongDocumentError: 4, InvalidCharacterError: 5, NoModificationAllowedError: 7, NotFoundError: 8, NotSupportedError: 9, InUseAttributeError: 10, InvalidStateError: 11, SyntaxError: 12, InvalidModificationError: 13, NamespaceError: 14, InvalidAccessError: 15, TypeMismatchError: 17, SecurityError: 18, NetworkError: 19, AbortError: 20, URLMismatchError: 21, QuotaExceededError: 22, TimeoutError: 23, InvalidNodeTypeError: 24, DataCloneError: 25, EncodingError: 0, NotReadableError: 0, UnknownError: 0, ConstraintError: 0, DataError: 0, TransactionInactiveError: 0, ReadOnlyError: 0, VersionError: 0, OperationError: 0, NotAllowedError: 0 }; var legacyCodes = { INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25 }; function createNonNativeDOMExceptionClass() { function DOMException(message, name) { // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message this[Symbol.toStringTag] = 'DOMException'; this._code = name in codes ? codes[name] : legacyCodes[name] || 0; this._name = name || 'Error'; this._message = message === undefined ? '' : '' + message; // Not String() which converts Symbols Object.defineProperty(this, 'code', { configurable: true, enumerable: true, writable: true, value: this._code }); if (name !== undefined) { Object.defineProperty(this, 'name', { configurable: true, enumerable: true, writable: true, value: this._name }); } if (message !== undefined) { Object.defineProperty(this, 'message', { configurable: true, enumerable: false, writable: true, value: this._message }); } } // Necessary for W3C tests which complains if `DOMException` has properties on its "own" prototype // class DummyDOMException extends Error {}; // Sometimes causing problems in Node var DummyDOMException = function DOMException() {}; DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing ['name', 'message'].forEach(function (prop) { Object.defineProperty(DummyDOMException.prototype, prop, { enumerable: true, get: function get() { if (!(this instanceof DOMException || this instanceof DummyDOMException || this instanceof Error)) { throw new TypeError('Illegal invocation'); } return this['_' + prop]; } }); }); // DOMException uses the same `toString` as `Error` Object.defineProperty(DummyDOMException.prototype, 'code', { configurable: true, enumerable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); DOMException.prototype = new DummyDOMException(); DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype'; Object.defineProperty(DOMException, 'prototype', { writable: false }); Object.keys(codes).forEach(function (codeName) { Object.defineProperty(DOMException.prototype, codeName, { enumerable: true, configurable: false, value: codes[codeName] }); Object.defineProperty(DOMException, codeName, { enumerable: true, configurable: false, value: codes[codeName] }); }); Object.keys(legacyCodes).forEach(function (codeName) { Object.defineProperty(DOMException.prototype, codeName, { enumerable: true, configurable: false, value: legacyCodes[codeName] }); Object.defineProperty(DOMException, codeName, { enumerable: true, configurable: false, value: legacyCodes[codeName] }); }); Object.defineProperty(DOMException.prototype, 'constructor', { writable: true, configurable: true, enumerable: false, value: DOMException }); return DOMException; } var ShimNonNativeDOMException = createNonNativeDOMExceptionClass(); /** * Creates a generic Error object * @returns {Error} */ function createNonNativeDOMException(name, message) { return new ShimNonNativeDOMException(message, name); } /** * Logs detailed error information to the console. * @param {string} name * @param {string} message * @param {string|Error|null} error */ function logError(name, message, error) { if (_CFG2.default.DEBUG) { if (error && error.message) { error = error.message; } var method = typeof console.error === 'function' ? 'error' : 'log'; console[method](name + ': ' + message + '. ' + (error || '')); console.trace && console.trace(); } } function isErrorOrDOMErrorOrDOMException(obj) { return obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && // We don't use util.isObj here as mutual dependency causing problems in Babel with browser typeof obj.name === 'string'; } /** * Finds the error argument. This is useful because some WebSQL callbacks * pass the error as the first argument, and some pass it as the second argument. * @param {array} args * @returns {Error|DOMException|undefined} */ function findError(args) { var err = void 0; if (args) { if (args.length === 1) { return args[0]; } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (isErrorOrDOMErrorOrDOMException(arg)) { return arg; } if (arg && typeof arg.message === 'string') { err = arg; } } } return err; } function webSQLErrback(webSQLErr) { var name = void 0, message = void 0; switch (webSQLErr.code) { case 4: { // SQLError.QUOTA_ERR name = 'QuotaExceededError'; message = 'The operation failed because there was not enough remaining storage space, or the storage quota was reached and the user declined to give more space to the database.'; break; } /* // Should a WebSQL timeout treat as IndexedDB `TransactionInactiveError` or `UnknownError`? case 7: { // SQLError.TIMEOUT_ERR // All transaction errors abort later, so no need to mark inactive name = 'TransactionInactiveError'; message = 'A request was placed against a transaction which is currently not active, or which is finished (Internal SQL Timeout).'; break; } */ default: { name = 'UnknownError'; message = 'The operation failed for reasons unrelated to the database itself and not covered by any other errors.'; break; } } message += ' (' + webSQLErr.message + ')--(' + webSQLErr.code + ')'; var err = createDOMException(name, message); err.sqlError = webSQLErr; return err; } var test = void 0, useNativeDOMException = false; // Test whether we can use the browser's native DOMException class try { test = createNativeDOMException('test name', 'test message'); if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') { // Native DOMException works as expected useNativeDOMException = true; } } catch (e) {} var createDOMException = void 0, ShimDOMException = void 0; if (useNativeDOMException) { exports.ShimDOMException = ShimDOMException = DOMException; exports.createDOMException = createDOMException = function createDOMException(name, message, error) { logError(name, message, error); return createNativeDOMException(name, message); }; } else { exports.ShimDOMException = ShimDOMException = ShimNonNativeDOMException; exports.createDOMException = createDOMException = function createDOMException(name, message, error) { logError(name, message, error); return createNonNativeDOMException(name, message); }; } exports.logError = logError; exports.findError = findError; exports.ShimDOMException = ShimDOMException; exports.createDOMException = createDOMException; exports.webSQLErrback = webSQLErrback; },{"./CFG":327}],329:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _DOMStringList$protot; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var cleanInterface = false; var testObject = { test: true }; // Test whether Object.defineProperty really works. if (Object.defineProperty) { try { Object.defineProperty(testObject, 'test', { enumerable: false }); if (testObject.test) { cleanInterface = true; } } catch (e) { // Object.defineProperty does not work as intended. } } /** * Shim the DOMStringList object. * */ var DOMStringList = function DOMStringList() { throw new TypeError('Illegal constructor'); }; DOMStringList.prototype = (_DOMStringList$protot = { constructor: DOMStringList, // Interface. contains: function contains(str) { if (!arguments.length) { throw new TypeError('DOMStringList.contains must be supplied a value'); } return this._items.includes(str); }, item: function item(key) { if (!arguments.length) { throw new TypeError('DOMStringList.item must be supplied a value'); } if (key < 0 || key >= this.length || !Number.isInteger(key)) { return null; } return this._items[key]; }, // Helpers. Should only be used internally. clone: function clone() { var stringList = DOMStringList.__createInstance(); stringList._items = this._items.slice(); stringList._length = this.length; stringList.addIndexes(); return stringList; }, addIndexes: function addIndexes() { for (var i = 0; i < this._items.length; i++) { this[i] = this._items[i]; } }, sortList: function sortList() { // http://w3c.github.io/IndexedDB/#sorted-list // https://tc39.github.io/ecma262/#sec-abstract-relational-comparison this._items.sort(); this.addIndexes(); return this._items; }, forEach: function forEach(cb, thisArg) { this._items.forEach(cb, thisArg); }, map: function map(cb, thisArg) { return this._items.map(cb, thisArg); }, indexOf: function indexOf(str) { return this._items.indexOf(str); }, push: function push(item) { this._items.push(item); this._length++; this.sortList(); }, splice: function splice() /* index, howmany, item1, ..., itemX */{ var _items; (_items = this._items).splice.apply(_items, arguments); this._length = this._items.length; for (var i in this) { if (i === String(parseInt(i, 10))) { delete this[i]; } } this.sortList(); } }, _defineProperty(_DOMStringList$protot, Symbol.toStringTag, 'DOMStringListPrototype'), _defineProperty(_DOMStringList$protot, Symbol.iterator, regeneratorRuntime.mark(function _callee() { var i; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: i = 0; case 1: if (!(i < this._items.length)) { _context.next = 6; break; } _context.next = 4; return this._items[i++]; case 4: _context.next = 1; break; case 6: case 'end': return _context.stop(); } } }, _callee, this); })), _DOMStringList$protot); Object.defineProperty(DOMStringList, Symbol.hasInstance, { value: function value(obj) { return {}.toString.call(obj) === 'DOMStringListPrototype'; } }); var DOMStringListAlias = DOMStringList; Object.defineProperty(DOMStringList, '__createInstance', { value: function value() { var DOMStringList = function DOMStringList() { this.toString = function () { return '[object DOMStringList]'; }; // Internal functions on the prototype have been made non-enumerable below. Object.defineProperty(this, 'length', { enumerable: true, get: function get() { return this._length; } }); this._items = []; this._length = 0; }; DOMStringList.prototype = DOMStringListAlias.prototype; return new DOMStringList(); } }); if (cleanInterface) { Object.defineProperty(DOMStringList, 'prototype', { writable: false }); var nonenumerableReadonly = ['addIndexes', 'sortList', 'forEach', 'map', 'indexOf', 'push', 'splice', 'constructor', '__createInstance']; nonenumerableReadonly.forEach(function (nonenumerableReadonly) { Object.defineProperty(DOMStringList.prototype, nonenumerableReadonly, { enumerable: false }); }); // Illegal invocations Object.defineProperty(DOMStringList.prototype, 'length', { configurable: true, enumerable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); var nonenumerableWritable = ['_items', '_length']; nonenumerableWritable.forEach(function (nonenumerableWritable) { Object.defineProperty(DOMStringList.prototype, nonenumerableWritable, { enumerable: false, writable: true }); }); } exports.default = DOMStringList; module.exports = exports['default']; },{}],330:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ShimEventTarget = exports.ShimCustomEvent = exports.ShimEvent = exports.createEvent = undefined; var _eventtarget = require('eventtarget'); var _util = require('./util'); var util = _interopRequireWildcard(_util); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function createEvent(type, debug, evInit) { var ev = new _eventtarget.ShimEvent(type, evInit); ev.debug = debug; return ev; } // We don't add within polyfill repo as might not always be the desired implementation Object.defineProperty(_eventtarget.ShimEvent, Symbol.hasInstance, { value: function value(obj) { return util.isObj(obj) && 'target' in obj && typeof obj.bubbles === 'boolean'; } }); exports.createEvent = createEvent; exports.ShimEvent = _eventtarget.ShimEvent; exports.ShimCustomEvent = _eventtarget.ShimCustomEvent; exports.ShimEventTarget = _eventtarget.ShimEventTarget; },{"./util":345,"eventtarget":298}],331:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.IDBCursorWithValue = exports.IDBCursor = undefined; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _IDBRequest = require('./IDBRequest'); var _IDBObjectStore = require('./IDBObjectStore'); var _IDBObjectStore2 = _interopRequireDefault(_IDBObjectStore); var _DOMException = require('./DOMException'); var _IDBKeyRange = require('./IDBKeyRange'); var _IDBFactory = require('./IDBFactory'); var _util = require('./util'); var util = _interopRequireWildcard(_util); var _IDBTransaction = require('./IDBTransaction'); var _IDBTransaction2 = _interopRequireDefault(_IDBTransaction); var _Key = require('./Key'); var Key = _interopRequireWildcard(_Key); var _Sca = require('./Sca'); var Sca = _interopRequireWildcard(_Sca); var _IDBIndex = require('./IDBIndex'); var _IDBIndex2 = _interopRequireDefault(_IDBIndex); var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The IndexedDB Cursor Object * http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBCursor * @param {IDBKeyRange} range * @param {string} direction * @param {IDBObjectStore} store * @param {IDBObjectStore|IDBIndex} source * @param {string} keyColumnName * @param {string} valueColumnName * @param {boolean} count */ function IDBCursor() { throw new TypeError('Illegal constructor'); } var IDBCursorAlias = IDBCursor; IDBCursor.__super = function IDBCursor(query, direction, store, source, keyColumnName, valueColumnName, count) { this[Symbol.toStringTag] = 'IDBCursor'; util.defineReadonlyProperties(this, ['key', 'primaryKey']); _IDBObjectStore2.default.__invalidStateIfDeleted(store); this.__indexSource = util.instanceOf(source, _IDBIndex2.default); if (this.__indexSource) _IDBIndex2.default.__invalidStateIfDeleted(source); _IDBTransaction2.default.__assertActive(store.transaction); var range = (0, _IDBKeyRange.convertValueToKeyRange)(query); if (direction !== undefined && !['next', 'prev', 'nextunique', 'prevunique'].includes(direction)) { throw new TypeError(direction + 'is not a valid cursor direction'); } Object.defineProperties(this, { // Babel is not respecting default writable false here, so make explicit source: { writable: false, value: source }, direction: { writable: false, value: direction || 'next' } }); this.__key = undefined; this.__primaryKey = undefined; this.__store = store; this.__range = range; this.__req = _IDBRequest.IDBRequest.__createInstance(); this.__req.__source = source; this.__req.__transaction = this.__store.transaction; this.__keyColumnName = keyColumnName; this.__valueColumnName = valueColumnName; this.__keyOnly = valueColumnName === 'key'; this.__valueDecoder = this.__keyOnly ? Key : Sca; this.__count = count; this.__prefetchedIndex = -1; this.__multiEntryIndex = this.__indexSource ? source.multiEntry : false; this.__unique = this.direction.includes('unique'); this.__sqlDirection = ['prev', 'prevunique'].includes(this.direction) ? 'DESC' : 'ASC'; if (range !== undefined) { // Encode the key range and cache the encoded values, so we don't have to re-encode them over and over range.__lowerCached = range.lower !== undefined && Key.encode(range.lower, this.__multiEntryIndex); range.__upperCached = range.upper !== undefined && Key.encode(range.upper, this.__multiEntryIndex); } this.__gotValue = true; this['continue'](); }; IDBCursor.__createInstance = function () { var IDBCursor = IDBCursorAlias.__super; IDBCursor.prototype = IDBCursorAlias.prototype; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new (Function.prototype.bind.apply(IDBCursor, [null].concat(args)))(); }; IDBCursor.prototype.__find = function () /* key, tx, success, error, recordsToLoad */{ if (this.__multiEntryIndex) { this.__findMultiEntry.apply(this, arguments); } else { this.__findBasic.apply(this, arguments); } }; IDBCursor.prototype.__findBasic = function (key, primaryKey, tx, success, error, recordsToLoad) { var continueCall = recordsToLoad !== undefined; recordsToLoad = recordsToLoad || 1; var me = this; var quotedKeyColumnName = util.sqlQuote(me.__keyColumnName); var quotedKey = util.sqlQuote('key'); var sql = ['SELECT * FROM', util.escapeStoreNameForSQL(me.__store.__currentName)]; var sqlValues = []; sql.push('WHERE', quotedKeyColumnName, 'NOT NULL'); (0, _IDBKeyRange.setSQLForKeyRange)(me.__range, quotedKeyColumnName, sql, sqlValues, true, true); // Determine the ORDER BY direction based on the cursor. var direction = me.__sqlDirection; var op = direction === 'ASC' ? '>' : '<'; if (primaryKey !== undefined) { sql.push('AND', quotedKey, op + '= ?'); // Key.convertValueToKey(primaryKey); // Already checked by `continuePrimaryKey` sqlValues.push(Key.encode(primaryKey)); } if (key !== undefined) { sql.push('AND', quotedKeyColumnName, op + '= ?'); // Key.convertValueToKey(key); // Already checked by `continue` or `continuePrimaryKey` sqlValues.push(Key.encode(key)); } else if (continueCall && me.__key !== undefined) { sql.push('AND', quotedKeyColumnName, op + ' ?'); // Key.convertValueToKey(me.__key); // Already checked when stored sqlValues.push(Key.encode(me.__key)); } if (!me.__count) { // 1. Sort by key sql.push('ORDER BY', quotedKeyColumnName, direction); // 2. Sort by primaryKey (if defined and not unique) if (!me.__unique && me.__keyColumnName !== 'key') { // Avoid adding 'key' twice sql.push(',', quotedKey, direction); } // 3. Sort by position (if defined) if (!me.__unique && me.__indexSource) { // 4. Sort by object store position (if defined and not unique) sql.push(',', util.sqlQuote(me.__valueColumnName), direction); } sql.push('LIMIT', recordsToLoad); } sql = sql.join(' '); _CFG2.default.DEBUG && console.log(sql, sqlValues); tx.executeSql(sql, sqlValues, function (tx, data) { if (me.__count) { success(undefined, data.rows.length, undefined); } else if (data.rows.length > 1) { me.__prefetchedIndex = 0; me.__prefetchedData = data.rows; _CFG2.default.DEBUG && console.log('Preloaded ' + me.__prefetchedData.length + ' records for cursor'); me.__decode(data.rows.item(0), success); } else if (data.rows.length === 1) { me.__decode(data.rows.item(0), success); } else { _CFG2.default.DEBUG && console.log('Reached end of cursors'); success(undefined, undefined, undefined); } }, function (tx, err) { _CFG2.default.DEBUG && console.log('Could not execute Cursor.continue', sql, sqlValues); error(err); }); }; IDBCursor.prototype.__findMultiEntry = function (key, primaryKey, tx, success, error) { var me = this; if (me.__prefetchedData && me.__prefetchedData.length === me.__prefetchedIndex) { _CFG2.default.DEBUG && console.log('Reached end of multiEntry cursor'); success(undefined, undefined, undefined); return; } var quotedKeyColumnName = util.sqlQuote(me.__keyColumnName); var sql = ['SELECT * FROM', util.escapeStoreNameForSQL(me.__store.__currentName)]; var sqlValues = []; sql.push('WHERE', quotedKeyColumnName, 'NOT NULL'); if (me.__range && me.__range.lower !== undefined && Array.isArray(me.__range.upper)) { if (me.__range.upper.indexOf(me.__range.lower) === 0) { sql.push('AND', quotedKeyColumnName, "LIKE ? ESCAPE '^'"); sqlValues.push('%' + util.sqlLIKEEscape(me.__range.__lowerCached.slice(0, -1)) + '%'); } } // Determine the ORDER BY direction based on the cursor. var direction = me.__sqlDirection; var op = direction === 'ASC' ? '>' : '<'; var quotedKey = util.sqlQuote('key'); if (primaryKey !== undefined) { sql.push('AND', quotedKey, op + '= ?'); // Key.convertValueToKey(primaryKey); // Already checked by `continuePrimaryKey` sqlValues.push(Key.encode(primaryKey)); } if (key !== undefined) { sql.push('AND', quotedKeyColumnName, op + '= ?'); // Key.convertValueToKey(key); // Already checked by `continue` or `continuePrimaryKey` sqlValues.push(Key.encode(key)); } else if (me.__key !== undefined) { sql.push('AND', quotedKeyColumnName, op + ' ?'); // Key.convertValueToKey(me.__key); // Already checked when entered sqlValues.push(Key.encode(me.__key)); } if (!me.__count) { // 1. Sort by key sql.push('ORDER BY', quotedKeyColumnName, direction); // 2. Sort by primaryKey (if defined and not unique) if (!me.__unique && me.__keyColumnName !== 'key') { // Avoid adding 'key' twice sql.push(',', util.sqlQuote('key'), direction); } // 3. Sort by position (if defined) if (!me.__unique && me.__indexSource) { // 4. Sort by object store position (if defined and not unique) sql.push(',', util.sqlQuote(me.__valueColumnName), direction); } } sql = sql.join(' '); _CFG2.default.DEBUG && console.log(sql, sqlValues); tx.executeSql(sql, sqlValues, function (tx, data) { if (data.rows.length > 0) { if (me.__count) { // Avoid caching and other processing below var ct = 0; for (var i = 0; i < data.rows.length; i++) { var rowItem = data.rows.item(i); var rowKey = Key.decode(rowItem[me.__keyColumnName], true); var matches = Key.findMultiEntryMatches(rowKey, me.__range); ct += matches.length; } success(undefined, ct, undefined); return; } var rows = []; for (var _i = 0; _i < data.rows.length; _i++) { var _rowItem = data.rows.item(_i); var _rowKey = Key.decode(_rowItem[me.__keyColumnName], true); var _matches = Key.findMultiEntryMatches(_rowKey, me.__range); for (var j = 0; j < _matches.length; j++) { var matchingKey = _matches[j]; var clone = { matchingKey: Key.encode(matchingKey, true), key: _rowItem.key }; clone[me.__keyColumnName] = _rowItem[me.__keyColumnName]; clone[me.__valueColumnName] = _rowItem[me.__valueColumnName]; rows.push(clone); } } var reverse = me.direction.indexOf('prev') === 0; rows.sort(function (a, b) { if (a.matchingKey.replace('[', 'z') < b.matchingKey.replace('[', 'z')) { return reverse ? 1 : -1; } if (a.matchingKey.replace('[', 'z') > b.matchingKey.replace('[', 'z')) { return reverse ? -1 : 1; } if (a.key < b.key) { return me.direction === 'prev' ? 1 : -1; } if (a.key > b.key) { return me.direction === 'prev' ? -1 : 1; } return 0; }); if (rows.length > 1) { me.__prefetchedIndex = 0; me.__prefetchedData = { data: rows, length: rows.length, item: function item(index) { return this.data[index]; } }; _CFG2.default.DEBUG && console.log('Preloaded ' + me.__prefetchedData.length + ' records for multiEntry cursor'); me.__decode(rows[0], success); } else if (rows.length === 1) { _CFG2.default.DEBUG && console.log('Reached end of multiEntry cursor'); me.__decode(rows[0], success); } else { _CFG2.default.DEBUG && console.log('Reached end of multiEntry cursor'); success(undefined, undefined, undefined); } } else { _CFG2.default.DEBUG && console.log('Reached end of multiEntry cursor'); success(undefined, undefined, undefined); } }, function (tx, err) { _CFG2.default.DEBUG && console.log('Could not execute Cursor.continue', sql, sqlValues); error(err); }); }; /** * Creates an "onsuccess" callback * @private */ IDBCursor.prototype.__onsuccess = function (success) { var me = this; return function (key, value, primaryKey) { if (me.__count) { success(value, me.__req); } else { if (key !== undefined) { me.__gotValue = true; } me.__key = key === undefined ? null : key; me.__primaryKey = primaryKey === undefined ? null : primaryKey; me.__value = value === undefined ? null : value; var result = key === undefined ? null : me; success(result, me.__req); } }; }; IDBCursor.prototype.__decode = function (rowItem, callback) { var me = this; if (me.__multiEntryIndex && me.__unique) { if (!me.__matchedKeys) { me.__matchedKeys = {}; } if (me.__matchedKeys[rowItem.matchingKey]) { callback(undefined, undefined, undefined); // eslint-disable-line standard/no-callback-literal return; } me.__matchedKeys[rowItem.matchingKey] = true; } var encKey = util.unescapeSQLiteResponse(me.__multiEntryIndex ? rowItem.matchingKey : rowItem[me.__keyColumnName]); var encVal = util.unescapeSQLiteResponse(rowItem[me.__valueColumnName]); var encPrimaryKey = util.unescapeSQLiteResponse(rowItem.key); var key = Key.decode(encKey, me.__multiEntryIndex); var val = me.__valueDecoder.decode(encVal); var primaryKey = Key.decode(encPrimaryKey); callback(key, val, primaryKey, encKey /*, encVal, encPrimaryKey */); }; IDBCursor.prototype.__sourceOrEffectiveObjStoreDeleted = function () { _IDBObjectStore2.default.__invalidStateIfDeleted(this.__store, "The cursor's effective object store has been deleted"); if (this.__indexSource) _IDBIndex2.default.__invalidStateIfDeleted(this.source, "The cursor's index source has been deleted"); }; IDBCursor.prototype.__invalidateCache = function () { this.__prefetchedData = null; }; IDBCursor.prototype.__continue = function (key, advanceContinue) { var me = this; var advanceState = me.__advanceCount !== undefined; _IDBTransaction2.default.__assertActive(me.__store.transaction); me.__sourceOrEffectiveObjStoreDeleted(); if (!me.__gotValue && !advanceContinue) { throw (0, _DOMException.createDOMException)('InvalidStateError', 'The cursor is being iterated or has iterated past its end.'); } if (key !== undefined) { Key.convertValueToKeyRethrowingAndIfInvalid(key); var cmpResult = (0, _IDBFactory.cmp)(key, me.key); if (cmpResult === 0 || me.direction.includes('next') && cmpResult === -1 || me.direction.includes('prev') && cmpResult === 1) { throw (0, _DOMException.createDOMException)('DataError', 'Cannot ' + (advanceState ? 'advance' : 'continue') + ' the cursor in an unexpected direction'); } } this.__continueFinish(key, undefined, advanceState); }; IDBCursor.prototype.__continueFinish = function (key, primaryKey, advanceState) { var me = this; var recordsToPreloadOnContinue = me.__advanceCount || _CFG2.default.cursorPreloadPackSize || 100; me.__gotValue = false; me.__req.__readyState = 'pending'; // Unset done flag me.__store.transaction.__pushToQueue(me.__req, function cursorContinue(tx, args, success, error, executeNextRequest) { function triggerSuccess(k, val, primKey) { if (advanceState) { if (me.__advanceCount >= 2 && k !== undefined) { me.__advanceCount--; me.__key = k; me.__continue(undefined, true); executeNextRequest(); // We don't call success yet but do need to advance the transaction queue return; } me.__advanceCount = undefined; } me.__onsuccess(success)(k, val, primKey); } if (me.__prefetchedData) { // We have pre-loaded data for the cursor me.__prefetchedIndex++; if (me.__prefetchedIndex < me.__prefetchedData.length) { me.__decode(me.__prefetchedData.item(me.__prefetchedIndex), function (k, val, primKey, encKey) { function checkKey() { var cmpResult = key === undefined || (0, _IDBFactory.cmp)(k, key); if (cmpResult > 0 || cmpResult === 0 && (me.__unique || primaryKey === undefined || (0, _IDBFactory.cmp)(primKey, primaryKey) >= 0)) { triggerSuccess(k, val, primKey); return; } cursorContinue(tx, args, success, error); } if (me.__unique && !me.__multiEntryIndex && encKey === Key.encode(me.key, me.__multiEntryIndex)) { cursorContinue(tx, args, success, error); return; } checkKey(); }); return; } } // No (or not enough) pre-fetched data, do query me.__find(key, primaryKey, tx, triggerSuccess, function () { me.__advanceCount = undefined; error.apply(undefined, arguments); }, recordsToPreloadOnContinue); }); }; IDBCursor.prototype['continue'] = function () /* key */{ this.__continue(arguments[0]); }; IDBCursor.prototype.continuePrimaryKey = function (key, primaryKey) { var me = this; _IDBTransaction2.default.__assertActive(me.__store.transaction); me.__sourceOrEffectiveObjStoreDeleted(); if (!me.__indexSource) { throw (0, _DOMException.createDOMException)('InvalidAccessError', '`continuePrimaryKey` may only be called on an index source.'); } if (!['next', 'prev'].includes(me.direction)) { throw (0, _DOMException.createDOMException)('InvalidAccessError', '`continuePrimaryKey` may not be called with unique cursors.'); } if (!me.__gotValue) { throw (0, _DOMException.createDOMException)('InvalidStateError', 'The cursor is being iterated or has iterated past its end.'); } Key.convertValueToKeyRethrowingAndIfInvalid(key); Key.convertValueToKeyRethrowingAndIfInvalid(primaryKey); var cmpResult = (0, _IDBFactory.cmp)(key, me.key); if (me.direction === 'next' && cmpResult === -1 || me.direction === 'prev' && cmpResult === 1) { throw (0, _DOMException.createDOMException)('DataError', 'Cannot continue the cursor in an unexpected direction'); } function noErrors() { me.__continueFinish(key, primaryKey, false); } if (cmpResult === 0) { Sca.encode(primaryKey, function (encPrimaryKey) { Sca.encode(me.primaryKey, function (encObjectStorePos) { if (encPrimaryKey === encObjectStorePos || me.direction === 'next' && encPrimaryKey < encObjectStorePos || me.direction === 'prev' && encPrimaryKey > encObjectStorePos) { throw (0, _DOMException.createDOMException)('DataError', 'Cannot continue the cursor in an unexpected direction'); } noErrors(); }); }); } else { noErrors(); } }; IDBCursor.prototype.advance = function (count) { var me = this; count = util.enforceRange(count, 'unsigned long'); if (count === 0) { throw new TypeError('Calling advance() with count argument 0'); } if (me.__gotValue) { // Only set the count if not running in error (otherwise will override earlier good advance calls) me.__advanceCount = count; } me.__continue(); }; IDBCursor.prototype.update = function (valueToUpdate) { var me = this; if (!arguments.length) throw new TypeError('A value must be passed to update()'); _IDBTransaction2.default.__assertActive(me.__store.transaction); me.__store.transaction.__assertWritable(); me.__sourceOrEffectiveObjStoreDeleted(); if (!me.__gotValue) { throw (0, _DOMException.createDOMException)('InvalidStateError', 'The cursor is being iterated or has iterated past its end.'); } if (me.__keyOnly) { throw (0, _DOMException.createDOMException)('InvalidStateError', 'This cursor method cannot be called when the key only flag has been set.'); } var request = me.__store.transaction.__createRequest(me); var key = me.primaryKey; function addToQueue(clonedValue) { _IDBObjectStore2.default.__storingRecordObjectStore(request, me.__store, clonedValue, false, key); } if (me.__store.keyPath !== null) { var _me$__store$__validat = me.__store.__validateKeyAndValueAndCloneValue(valueToUpdate, undefined, true), _me$__store$__validat2 = _slicedToArray(_me$__store$__validat, 2), evaluatedKey = _me$__store$__validat2[0], clonedValue = _me$__store$__validat2[1]; if ((0, _IDBFactory.cmp)(me.primaryKey, evaluatedKey) !== 0) { throw (0, _DOMException.createDOMException)('DataError', 'The key of the supplied value to `update` is not equal to the cursor\'s effective key'); } addToQueue(clonedValue); } else { var _clonedValue = Sca.clone(valueToUpdate); addToQueue(_clonedValue); } return request; }; IDBCursor.prototype['delete'] = function () { var me = this; _IDBTransaction2.default.__assertActive(me.__store.transaction); me.__store.transaction.__assertWritable(); me.__sourceOrEffectiveObjStoreDeleted(); if (!me.__gotValue) { throw (0, _DOMException.createDOMException)('InvalidStateError', 'The cursor is being iterated or has iterated past its end.'); } if (me.__keyOnly) { throw (0, _DOMException.createDOMException)('InvalidStateError', 'This cursor method cannot be called when the key only flag has been set.'); } return this.__store.transaction.__addToTransactionQueue(function cursorDelete(tx, args, success, error) { me.__find(undefined, undefined, tx, function (key, value, primaryKey) { var sql = 'DELETE FROM ' + util.escapeStoreNameForSQL(me.__store.__currentName) + ' WHERE "key" = ?'; _CFG2.default.DEBUG && console.log(sql, key, primaryKey); // Key.convertValueToKey(primaryKey); // Already checked when entered tx.executeSql(sql, [util.escapeSQLiteStatement(Key.encode(primaryKey))], function (tx, data) { if (data.rowsAffected === 1) { me.__store.__cursors.forEach(function (cursor) { cursor.__invalidateCache(); // Delete }); success(undefined); } else { error('No rows with key found' + key); } }, function (tx, data) { error(data); }); }, error); }, undefined, me); }; IDBCursor.prototype[Symbol.toStringTag] = 'IDBCursorPrototype'; ['source', 'direction', 'key', 'primaryKey'].forEach(function (prop) { Object.defineProperty(IDBCursor.prototype, prop, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); }); Object.defineProperty(IDBCursor, 'prototype', { writable: false }); function IDBCursorWithValue() { throw new TypeError('Illegal constructor'); } IDBCursorWithValue.prototype = Object.create(IDBCursor.prototype); Object.defineProperty(IDBCursorWithValue.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBCursorWithValue }); var IDBCursorWithValueAlias = IDBCursorWithValue; IDBCursorWithValue.__createInstance = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } function IDBCursorWithValue() { var _IDBCursor$__super; (_IDBCursor$__super = IDBCursor.__super).call.apply(_IDBCursor$__super, [this].concat(args)); this[Symbol.toStringTag] = 'IDBCursorWithValue'; util.defineReadonlyProperties(this, 'value'); } IDBCursorWithValue.prototype = IDBCursorWithValueAlias.prototype; return new IDBCursorWithValue(); }; Object.defineProperty(IDBCursorWithValue.prototype, 'value', { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); IDBCursorWithValue.prototype[Symbol.toStringTag] = 'IDBCursorWithValuePrototype'; Object.defineProperty(IDBCursorWithValue, 'prototype', { writable: false }); exports.IDBCursor = IDBCursor; exports.IDBCursorWithValue = IDBCursorWithValue; },{"./CFG":327,"./DOMException":328,"./IDBFactory":333,"./IDBIndex":334,"./IDBKeyRange":335,"./IDBObjectStore":336,"./IDBRequest":337,"./IDBTransaction":338,"./Key":340,"./Sca":341,"./util":345}],332:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _DOMException = require('./DOMException'); var _Event = require('./Event'); var _util = require('./util'); var util = _interopRequireWildcard(_util); var _DOMStringList = require('./DOMStringList'); var _DOMStringList2 = _interopRequireDefault(_DOMStringList); var _IDBObjectStore = require('./IDBObjectStore'); var _IDBObjectStore2 = _interopRequireDefault(_IDBObjectStore); var _IDBTransaction = require('./IDBTransaction'); var _IDBTransaction2 = _interopRequireDefault(_IDBTransaction); var _Sca = require('./Sca'); var Sca = _interopRequireWildcard(_Sca); var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); var _eventtarget = require('eventtarget'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var listeners = ['onabort', 'onclose', 'onerror', 'onversionchange']; var readonlyProperties = ['name', 'version', 'objectStoreNames']; /** * IDB Database Object * http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#database-interface * @constructor */ function IDBDatabase() { throw new TypeError('Illegal constructor'); } var IDBDatabaseAlias = IDBDatabase; IDBDatabase.__createInstance = function (db, name, oldVersion, version, storeProperties) { function IDBDatabase() { var _this = this; this[Symbol.toStringTag] = 'IDBDatabase'; util.defineReadonlyProperties(this, readonlyProperties); this.__db = db; this.__closed = false; this.__oldVersion = oldVersion; this.__version = version; this.__name = name; listeners.forEach(function (listener) { Object.defineProperty(_this, listener, { enumerable: true, configurable: true, get: function get() { return this['__' + listener]; }, set: function set(val) { this['__' + listener] = val; } }); }); listeners.forEach(function (l) { _this[l] = null; }); this.__setOptions({ legacyOutputDidListenersThrowFlag: true // Event hook for IndexedB }); this.__transactions = []; this.__objectStores = {}; this.__objectStoreNames = _DOMStringList2.default.__createInstance(); var itemCopy = {}; var _loop = function _loop(i) { var item = storeProperties.rows.item(i); // Safari implements `item` getter return object's properties // as readonly, so we copy all its properties (except our // custom `currNum` which we don't need) onto a new object itemCopy.name = item.name; itemCopy.keyPath = Sca.decode(item.keyPath); ['autoInc', 'indexList'].forEach(function (prop) { itemCopy[prop] = JSON.parse(item[prop]); }); itemCopy.idbdb = _this; var store = _IDBObjectStore2.default.__createInstance(itemCopy); _this.__objectStores[store.name] = store; _this.objectStoreNames.push(store.name); }; for (var i = 0; i < storeProperties.rows.length; i++) { _loop(i); } this.__oldObjectStoreNames = this.objectStoreNames.clone(); } IDBDatabase.prototype = IDBDatabaseAlias.prototype; return new IDBDatabase(); }; IDBDatabase.prototype = _eventtarget.EventTargetFactory.createInstance(); IDBDatabase.prototype[Symbol.toStringTag] = 'IDBDatabasePrototype'; /** * Creates a new object store. * @param {string} storeName * @param {object} [createOptions] * @returns {IDBObjectStore} */ IDBDatabase.prototype.createObjectStore = function (storeName /* , createOptions */) { var createOptions = arguments[1]; storeName = String(storeName); // W3C test within IDBObjectStore.js seems to accept string conversion if (!(this instanceof IDBDatabase)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No object store name was specified'); } _IDBTransaction2.default.__assertVersionChange(this.__versionTransaction); // this.__versionTransaction may not exist if called mistakenly by user in onsuccess _IDBTransaction2.default.__assertNotFinishedObjectStoreMethod(this.__versionTransaction); _IDBTransaction2.default.__assertActive(this.__versionTransaction); createOptions = Object.assign({}, createOptions); var keyPath = createOptions.keyPath; keyPath = keyPath === undefined ? null : keyPath = util.convertToSequenceDOMString(keyPath); if (keyPath !== null && !util.isValidKeyPath(keyPath)) { throw (0, _DOMException.createDOMException)('SyntaxError', 'The keyPath argument contains an invalid key path.'); } if (this.__objectStores[storeName] && !this.__objectStores[storeName].__pendingDelete) { throw (0, _DOMException.createDOMException)('ConstraintError', 'Object store "' + storeName + '" already exists in ' + this.name); } var autoIncrement = createOptions.autoIncrement; if (autoIncrement && (keyPath === '' || Array.isArray(keyPath))) { throw (0, _DOMException.createDOMException)('InvalidAccessError', 'With autoIncrement set, the keyPath argument must not be an array or empty string.'); } /** @name IDBObjectStoreProperties **/ var storeProperties = { name: storeName, keyPath: keyPath, autoInc: autoIncrement, indexList: {}, idbdb: this }; var store = _IDBObjectStore2.default.__createInstance(storeProperties, this.__versionTransaction); return _IDBObjectStore2.default.__createObjectStore(this, store); }; /** * Deletes an object store. * @param {string} storeName */ IDBDatabase.prototype.deleteObjectStore = function (storeName) { if (!(this instanceof IDBDatabase)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No object store name was specified'); } _IDBTransaction2.default.__assertVersionChange(this.__versionTransaction); _IDBTransaction2.default.__assertNotFinishedObjectStoreMethod(this.__versionTransaction); _IDBTransaction2.default.__assertActive(this.__versionTransaction); var store = this.__objectStores[storeName]; if (!store) { throw (0, _DOMException.createDOMException)('NotFoundError', 'Object store "' + storeName + '" does not exist in ' + this.name); } _IDBObjectStore2.default.__deleteObjectStore(this, store); }; IDBDatabase.prototype.close = function () { if (!(this instanceof IDBDatabase)) { throw new TypeError('Illegal invocation'); } this.__closed = true; if (this.__unblocking) { this.__unblocking.check(); } }; /** * Starts a new transaction. * @param {string|string[]} storeNames * @param {string} mode * @returns {IDBTransaction} */ IDBDatabase.prototype.transaction = function (storeNames /* , mode */) { var _this2 = this; var mode = arguments[1]; storeNames = typeof storeNames === 'string' ? [storeNames] : util.isIterable(storeNames) ? [].concat(_toConsumableArray(new Set( // to be unique util.convertToSequenceDOMString(storeNames) // iterables have `ToString` applied (and we convert to array for convenience) ))).sort() // must be sorted : function () { throw new TypeError('You must supply a valid `storeNames` to `IDBDatabase.transaction`'); }(); // Since SQLite (at least node-websql and definitely WebSQL) requires // locking of the whole database, to allow simultaneous readwrite // operations on transactions without overlapping stores, we'd probably // need to save the stores in separate databases (we could also consider // prioritizing readonly but not starving readwrite). // Even for readonly transactions, due to [issue 17](https://github.com/nolanlawson/node-websql/issues/17), // we're not currently actually running the SQL requests in parallel. if (typeof mode === 'number') { mode = mode === 1 ? 'readwrite' : 'readonly'; _CFG2.default.DEBUG && console.log('Mode should be a string, but was specified as ', mode); // Todo Deprecated: Remove this option as no longer in spec } else { mode = mode || 'readonly'; } _IDBTransaction2.default.__assertNotVersionChange(this.__versionTransaction); if (this.__closed) { throw (0, _DOMException.createDOMException)('InvalidStateError', 'An attempt was made to start a new transaction on a database connection that is not open'); } var objectStoreNames = _DOMStringList2.default.__createInstance(); storeNames.forEach(function (storeName) { if (!_this2.objectStoreNames.contains(storeName)) { throw (0, _DOMException.createDOMException)('NotFoundError', 'The "' + storeName + '" object store does not exist'); } objectStoreNames.push(storeName); }); if (storeNames.length === 0) { throw (0, _DOMException.createDOMException)('InvalidAccessError', 'No valid object store names were specified'); } if (mode !== 'readonly' && mode !== 'readwrite') { throw new TypeError('Invalid transaction mode: ' + mode); } // Do not set __active flag to false yet: https://github.com/w3c/IndexedDB/issues/87 var trans = _IDBTransaction2.default.__createInstance(this, objectStoreNames, mode); this.__transactions.push(trans); return trans; }; // Todo __forceClose: Add tests for `__forceClose` IDBDatabase.prototype.__forceClose = function (msg) { var me = this; me.close(); var ct = 0; me.__transactions.forEach(function (trans) { trans.on__abort = function () { ct++; if (ct === me.__transactions.length) { // Todo __forceClose: unblock any pending `upgradeneeded` or `deleteDatabase` calls var evt = (0, _Event.createEvent)('close'); setTimeout(function () { me.dispatchEvent(evt); }); } }; trans.__abortTransaction((0, _DOMException.createDOMException)('AbortError', 'The connection was force-closed: ' + (msg || ''))); }); }; listeners.forEach(function (listener) { Object.defineProperty(IDBDatabase.prototype, listener, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); }, set: function set(val) { throw new TypeError('Illegal invocation'); } }); }); readonlyProperties.forEach(function (prop) { Object.defineProperty(IDBDatabase.prototype, prop, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); }); Object.defineProperty(IDBDatabase.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBDatabase }); Object.defineProperty(IDBDatabase, 'prototype', { writable: false }); exports.default = IDBDatabase; module.exports = exports['default']; },{"./CFG":327,"./DOMException":328,"./DOMStringList":329,"./Event":330,"./IDBObjectStore":336,"./IDBTransaction":338,"./Sca":341,"./util":345,"eventtarget":298}],333:[function(require,module,exports){ (function (process){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.shimIndexedDB = exports.cmp = exports.IDBFactory = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* globals location, Event */ var _Event = require('./Event'); var _IDBVersionChangeEvent = require('./IDBVersionChangeEvent'); var _IDBVersionChangeEvent2 = _interopRequireDefault(_IDBVersionChangeEvent); var _DOMException = require('./DOMException'); var _IDBRequest = require('./IDBRequest'); var _DOMStringList = require('./DOMStringList'); var _DOMStringList2 = _interopRequireDefault(_DOMStringList); var _util = require('./util'); var util = _interopRequireWildcard(_util); var _Key = require('./Key'); var Key = _interopRequireWildcard(_Key); var _IDBTransaction = require('./IDBTransaction'); var _IDBTransaction2 = _interopRequireDefault(_IDBTransaction); var _IDBDatabase = require('./IDBDatabase'); var _IDBDatabase2 = _interopRequireDefault(_IDBDatabase); var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); var _syncPromise = require('sync-promise'); var _syncPromise2 = _interopRequireDefault(_syncPromise); var _path = require('path'); var _path2 = _interopRequireDefault(_path); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var getOrigin = function getOrigin() { return (typeof location === 'undefined' ? 'undefined' : _typeof(location)) !== 'object' || !location ? 'null' : location.origin; }; var hasNullOrigin = function hasNullOrigin() { return _CFG2.default.checkOrigin !== false && getOrigin() === 'null'; }; // Todo: This really should be process and tab-independent so the // origin could vary; in the browser, this might be through a // `SharedWorker` var connectionQueue = {}; function processNextInConnectionQueue(name) { var origin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getOrigin(); var queueItems = connectionQueue[origin][name]; if (!queueItems[0]) { // Nothing left to process return; } var _queueItems$ = queueItems[0], req = _queueItems$.req, cb = _queueItems$.cb; // Keep in queue to prevent continuation function removeFromQueue() { queueItems.shift(); processNextInConnectionQueue(name, origin); } req.addEventListener('success', removeFromQueue); req.addEventListener('error', removeFromQueue); cb(req); } function addRequestToConnectionQueue(req, name) { var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : getOrigin(); var cb = arguments[3]; if (!connectionQueue[origin][name]) { connectionQueue[origin][name] = []; } connectionQueue[origin][name].push({ req: req, cb: cb }); if (connectionQueue[origin][name].length === 1) { // If there are no items in the queue, we have to start it processNextInConnectionQueue(name, origin); } } function triggerAnyVersionChangeAndBlockedEvents(openConnections, req, oldVersion, newVersion) { // Todo: For Node (and in browser using service workers if available?) the // connections ought to involve those in any process; should also // auto-close if unloading var connectionIsClosed = function connectionIsClosed(connection) { return connection.__closed; }; var connectionsClosed = function connectionsClosed() { return openConnections.every(connectionIsClosed); }; return openConnections.reduce(function (promises, entry) { if (connectionIsClosed(entry)) { return promises; } return promises.then(function () { if (connectionIsClosed(entry)) { // Prior onversionchange must have caused this connection to be closed return; } var e = new _IDBVersionChangeEvent2.default('versionchange', { oldVersion: oldVersion, newVersion: newVersion }); return new _syncPromise2.default(function (resolve) { setTimeout(function () { entry.dispatchEvent(e); // No need to catch errors resolve(); }); }); }); }, _syncPromise2.default.resolve()).then(function () { if (!connectionsClosed()) { return new _syncPromise2.default(function (resolve) { var unblocking = { check: function check() { if (connectionsClosed()) { resolve(); } } }; var e = new _IDBVersionChangeEvent2.default('blocked', { oldVersion: oldVersion, newVersion: newVersion }); setTimeout(function () { req.dispatchEvent(e); // No need to catch errors if (!connectionsClosed()) { openConnections.forEach(function (connection) { if (!connectionIsClosed(connection)) { connection.__unblocking = unblocking; } }); } else { resolve(); } }); }); } }); } var websqlDBCache = {}; var sysdb = void 0; var nameCounter = 0; function getLatestCachedWebSQLVersion(name) { return Object.keys(websqlDBCache[name]).map(Number).reduce(function (prev, curr) { return curr > prev ? curr : prev; }, 0); } function getLatestCachedWebSQLDB(name) { return websqlDBCache[name] && websqlDBCache[name][// eslint-disable-line standard/computed-property-even-spacing getLatestCachedWebSQLVersion()]; } function cleanupDatabaseResources(__openDatabase, name, escapedDatabaseName, databaseDeleted, dbError) { var useMemoryDatabase = typeof _CFG2.default.memoryDatabase === 'string'; if (useMemoryDatabase) { var latestSQLiteDBCached = websqlDBCache[name] ? getLatestCachedWebSQLDB(name) : null; if (!latestSQLiteDBCached) { console.warn('Could not find a memory database instance to delete.'); databaseDeleted(); return; } var _sqliteDB = latestSQLiteDBCached._db && latestSQLiteDBCached._db._db; if (!_sqliteDB || !_sqliteDB.close) { console.error('The `openDatabase` implementation does not have the expected `._db._db.close` method for closing the database'); return; } _sqliteDB.close(function (err) { if (err) { console.warn('Error closing (destroying) memory database'); return; } databaseDeleted(); }); return; } if (_CFG2.default.deleteDatabaseFiles !== false && {}.toString.call(process) === '[object process]') { require('fs').unlink(require('path').resolve(escapedDatabaseName), function (err) { if (err && err.code !== 'ENOENT') { // Ignore if file is already deleted dbError({ code: 0, message: 'Error removing database file: ' + escapedDatabaseName + ' ' + err }); return; } databaseDeleted(); }); return; } var sqliteDB = __openDatabase(_path2.default.join(_CFG2.default.databaseBasePath || '', escapedDatabaseName), 1, name, _CFG2.default.DEFAULT_DB_SIZE); sqliteDB.transaction(function (tx) { tx.executeSql('SELECT "name" FROM __sys__', [], function (tx, data) { var tables = data.rows; (function deleteTables(i) { if (i >= tables.length) { // If all tables are deleted, delete the housekeeping tables tx.executeSql('DROP TABLE IF EXISTS __sys__', [], function () { databaseDeleted(); }, dbError); } else { // Delete all tables in this database, maintained in the sys table tx.executeSql('DROP TABLE ' + util.escapeStoreNameForSQL(util.unescapeSQLiteResponse( // Avoid double-escaping tables.item(i).name)), [], function () { deleteTables(i + 1); }, function () { deleteTables(i + 1); }); } })(0); }, function (e) { // __sys__ table does not exist, but that does not mean delete did not happen databaseDeleted(); }); }); } /** * Creates the sysDB to keep track of version numbers for databases **/ function createSysDB(__openDatabase, success, failure) { function sysDbCreateError(tx, err) { err = (0, _DOMException.webSQLErrback)(err); _CFG2.default.DEBUG && console.log('Error in sysdb transaction - when creating dbVersions', err); failure(err); } if (sysdb) { success(); } else { sysdb = __openDatabase(typeof _CFG2.default.memoryDatabase === 'string' ? _CFG2.default.memoryDatabase : _path2.default.join(typeof _CFG2.default.sysDatabaseBasePath === 'string' ? _CFG2.default.sysDatabaseBasePath : _CFG2.default.databaseBasePath || '', '__sysdb__' + (_CFG2.default.addSQLiteExtension !== false ? '.sqlite' : '')), 1, 'System Database', _CFG2.default.DEFAULT_DB_SIZE); sysdb.transaction(function (systx) { systx.executeSql('CREATE TABLE IF NOT EXISTS dbVersions (name BLOB, version INT);', [], success, sysDbCreateError); }, sysDbCreateError); } } /** * IDBFactory Class * https://w3c.github.io/IndexedDB/#idl-def-IDBFactory * @constructor */ function IDBFactory() { throw new TypeError('Illegal constructor'); } var IDBFactoryAlias = IDBFactory; IDBFactory.__createInstance = function () { function IDBFactory() { this[Symbol.toStringTag] = 'IDBFactory'; this.modules = { // Export other shims (especially for testing) Event: typeof Event !== 'undefined' ? Event : _Event.ShimEvent, Error: Error, // For test comparisons ShimEvent: _Event.ShimEvent, ShimCustomEvent: _Event.ShimCustomEvent, ShimEventTarget: _Event.ShimEventTarget, ShimDOMException: _DOMException.ShimDOMException, ShimDOMStringList: _DOMStringList2.default, IDBFactory: IDBFactoryAlias }; this.utils = { createDOMException: _DOMException.createDOMException }; // Expose for ease in simulating such exceptions during testing this.__connections = {}; } IDBFactory.prototype = IDBFactoryAlias.prototype; return new IDBFactory(); }; /** * The IndexedDB Method to create a new database and return the DB * @param {string} name * @param {number} version */ IDBFactory.prototype.open = function (name /* , version */) { var me = this; if (!(me instanceof IDBFactory)) { throw new TypeError('Illegal invocation'); } var version = arguments[1]; if (arguments.length === 0) { throw new TypeError('Database name is required'); } if (version !== undefined) { version = util.enforceRange(version, 'unsigned long long'); if (version === 0) { throw new TypeError('Version cannot be 0'); } } if (hasNullOrigin()) { throw (0, _DOMException.createDOMException)('SecurityError', 'Cannot open an IndexedDB database from an opaque origin.'); } var req = _IDBRequest.IDBOpenDBRequest.__createInstance(); var calledDbCreateError = false; if (_CFG2.default.autoName && name === '') { name = 'autoNamedDatabase_' + nameCounter++; } name = String(name); // cast to a string var sqlSafeName = util.escapeSQLiteStatement(name); var useMemoryDatabase = typeof _CFG2.default.memoryDatabase === 'string'; var useDatabaseCache = _CFG2.default.cacheDatabaseInstances !== false || useMemoryDatabase; var escapedDatabaseName = void 0; try { escapedDatabaseName = util.escapeDatabaseNameForSQLAndFiles(name); } catch (err) { throw err; // new TypeError('You have supplied a database name which does not match the currently supported configuration, possibly due to a length limit enforced for Node compatibility.'); } function dbCreateError(tx, err) { if (calledDbCreateError) { return; } err = err ? (0, _DOMException.webSQLErrback)(err) : tx; calledDbCreateError = true; // Re: why bubbling here (and how cancelable is only really relevant for `window.onerror`) see: https://github.com/w3c/IndexedDB/issues/86 var evt = (0, _Event.createEvent)('error', err, { bubbles: true, cancelable: true }); req.__readyState = 'done'; req.__error = err; req.__result = undefined; req.dispatchEvent(evt); } function openDB(oldVersion) { var db = void 0; if ((useMemoryDatabase || useDatabaseCache) && name in websqlDBCache && websqlDBCache[name][version]) { db = websqlDBCache[name][version]; } else { db = me.__openDatabase(useMemoryDatabase ? _CFG2.default.memoryDatabase : _path2.default.join(_CFG2.default.databaseBasePath || '', escapedDatabaseName), 1, name, _CFG2.default.DEFAULT_DB_SIZE); if (useDatabaseCache) { websqlDBCache[name][version] = db; } } if (version === undefined) { version = oldVersion || 1; } if (oldVersion > version) { var err = (0, _DOMException.createDOMException)('VersionError', 'An attempt was made to open a database using a lower version than the existing version.', version); dbCreateError(err); return; } db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS __sys__ (name BLOB, keyPath BLOB, autoInc BOOLEAN, indexList BLOB, currNum INTEGER)', [], function () { tx.executeSql('SELECT "name", "keyPath", "autoInc", "indexList" FROM __sys__', [], function (tx, data) { function finishRequest() { req.__readyState = 'done'; req.__result = connection; } var connection = _IDBDatabase2.default.__createInstance(db, name, oldVersion, version, data); if (!me.__connections[name]) { me.__connections[name] = []; } me.__connections[name].push(connection); if (oldVersion < version) { var openConnections = me.__connections[name].slice(0, -1); triggerAnyVersionChangeAndBlockedEvents(openConnections, req, oldVersion, version).then(function () { // DB Upgrade in progress var sysdbFinishedCb = function sysdbFinishedCb(systx, err, cb) { if (err) { try { systx.executeSql('ROLLBACK', [], cb, cb); } catch (er) { // Browser may fail with expired transaction above so // no choice but to manually revert sysdb.transaction(function (systx) { function reportError(msg) { throw new Error('Unable to roll back upgrade transaction!' + (msg || '')); } // Attempt to revert if (oldVersion === 0) { systx.executeSql('DELETE FROM dbVersions WHERE "name" = ?', [sqlSafeName], function () { cb(reportError); }, reportError); } else { systx.executeSql('UPDATE dbVersions SET "version" = ? WHERE "name" = ?', [oldVersion, sqlSafeName], cb, reportError); } }); } return; } cb(); // In browser, should auto-commit }; sysdb.transaction(function (systx) { function versionSet() { var e = new _IDBVersionChangeEvent2.default('upgradeneeded', { oldVersion: oldVersion, newVersion: version }); req.__result = connection; req.__transaction = req.__result.__versionTransaction = _IDBTransaction2.default.__createInstance(req.__result, req.__result.objectStoreNames, 'versionchange'); req.__readyState = 'done'; req.transaction.__addNonRequestToTransactionQueue(function onupgradeneeded(tx, args, finished, error) { req.dispatchEvent(e); if (e.__legacyOutputDidListenersThrowError) { (0, _DOMException.logError)('Error', 'An error occurred in an upgradeneeded handler attached to request chain', e.__legacyOutputDidListenersThrowError); // We do nothing else with this error as per spec req.transaction.__abortTransaction((0, _DOMException.createDOMException)('AbortError', 'A request was aborted.')); return; } finished(); }); req.transaction.on__beforecomplete = function (ev) { req.__result.__versionTransaction = null; sysdbFinishedCb(systx, false, function () { req.transaction.__transFinishedCb(false, function () { if (useDatabaseCache) { if (name in websqlDBCache) { delete websqlDBCache[name][version]; } } ev.complete(); req.__transaction = null; }); }); }; req.transaction.on__preabort = function () { // We ensure any cache is deleted before any request error events fire and try to reopen if (useDatabaseCache) { if (name in websqlDBCache) { delete websqlDBCache[name][version]; } } }; req.transaction.on__abort = function () { req.__transaction = null; connection.close(); setTimeout(function () { var err = (0, _DOMException.createDOMException)('AbortError', 'The upgrade transaction was aborted.'); sysdbFinishedCb(systx, err, function (reportError) { if (oldVersion === 0) { cleanupDatabaseResources(me.__openDatabase, name, escapedDatabaseName, dbCreateError.bind(null, err), reportError || dbCreateError); return; } dbCreateError(err); }); }); }; req.transaction.on__complete = function () { if (req.__result.__closed) { req.__transaction = null; var _err = (0, _DOMException.createDOMException)('AbortError', 'The connection has been closed.'); dbCreateError(_err); return; } // Since this is running directly after `IDBTransaction.complete`, // there should be a new task. However, while increasing the // timeout 1ms in `IDBTransaction.__executeRequests` can allow // `IDBOpenDBRequest.onsuccess` to trigger faster than a new // transaction as required by "transaction-create_in_versionchange" in // w3c/Transaction.js (though still on a timeout separate from this // preceding `IDBTransaction.oncomplete`), this causes a race condition // somehow with old transactions (e.g., for the Mocha test, // in `IDBObjectStore.deleteIndex`, "should delete an index that was // created in a previous transaction"). // setTimeout(() => { // Todo: Waiting on confirmation re: positioning here of // `readyState` (and `result`)--see https://github.com/w3c/IndexedDB/issues/161 // Note, however, that the readyState and result will be reset anyways // req.__readyState = 'pending'; // req.__result = undefined; finishRequest(); req.__transaction = null; var e = (0, _Event.createEvent)('success'); req.dispatchEvent(e); // }); }; } if (oldVersion === 0) { systx.executeSql('INSERT INTO dbVersions VALUES (?,?)', [sqlSafeName, version], versionSet, dbCreateError); } else { systx.executeSql('UPDATE dbVersions SET "version" = ? WHERE "name" = ?', [version, sqlSafeName], versionSet, dbCreateError); } }, dbCreateError, null, function (currentTask, err, done, rollback, commit) { if (currentTask.readOnly || err) { return true; } sysdbFinishedCb = function sysdbFinishedCb(systx, err, cb) { if (err) { rollback(err, cb); } else { commit(cb); } }; return false; }); }); } else { finishRequest(); var e = (0, _Event.createEvent)('success'); req.dispatchEvent(e); } }, dbCreateError); }, dbCreateError); }, dbCreateError); } addRequestToConnectionQueue(req, name, /* origin */undefined, function (req) { var latestCachedVersion = void 0; if (useDatabaseCache) { if (!(name in websqlDBCache)) { websqlDBCache[name] = {}; } if (version === undefined) { latestCachedVersion = getLatestCachedWebSQLVersion(name); } else if (websqlDBCache[name][version]) { latestCachedVersion = version; } } if (latestCachedVersion) { openDB(latestCachedVersion); } else { createSysDB(me.__openDatabase, function () { sysdb.readTransaction(function (sysReadTx) { sysReadTx.executeSql('SELECT "version" FROM dbVersions WHERE "name" = ?', [sqlSafeName], function (sysReadTx, data) { if (data.rows.length === 0) { // Database with this name does not exist openDB(0); } else { openDB(data.rows.item(0).version); } }, dbCreateError); }, dbCreateError); }, dbCreateError); } }); return req; }; /** * Deletes a database * @param {string} name * @returns {IDBOpenDBRequest} */ IDBFactory.prototype.deleteDatabase = function (name) { var me = this; if (!(me instanceof IDBFactory)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('Database name is required'); } if (hasNullOrigin()) { throw (0, _DOMException.createDOMException)('SecurityError', 'Cannot delete an IndexedDB database from an opaque origin.'); } name = String(name); // cast to a string var sqlSafeName = util.escapeSQLiteStatement(name); var escapedDatabaseName = void 0; try { escapedDatabaseName = util.escapeDatabaseNameForSQLAndFiles(name); } catch (err) { throw err; // throw new TypeError('You have supplied a database name which does not match the currently supported configuration, possibly due to a length limit enforced for Node compatibility.'); } var useMemoryDatabase = typeof _CFG2.default.memoryDatabase === 'string'; var useDatabaseCache = _CFG2.default.cacheDatabaseInstances !== false || useMemoryDatabase; var req = _IDBRequest.IDBOpenDBRequest.__createInstance(); var calledDBError = false; var version = 0; var sysdbFinishedCbDelete = function sysdbFinishedCbDelete(err, cb) { cb(err); }; // Although the spec has no specific conditions where an error // may occur in `deleteDatabase`, it does provide for // `UnknownError` as we may require upon a SQL deletion error function dbError(tx, err) { if (calledDBError || err === true) { return; } err = (0, _DOMException.webSQLErrback)(err || tx); sysdbFinishedCbDelete(true, function () { req.__readyState = 'done'; req.__error = err; req.__result = undefined; // Re: why bubbling here (and how cancelable is only really relevant for `window.onerror`) see: https://github.com/w3c/IndexedDB/issues/86 var e = (0, _Event.createEvent)('error', err, { bubbles: true, cancelable: true }); req.dispatchEvent(e); calledDBError = true; }); } addRequestToConnectionQueue(req, name, /* origin */undefined, function (req) { createSysDB(me.__openDatabase, function () { // function callback (cb) { cb(); } // callback(function () { function completeDatabaseDelete() { req.__result = undefined; req.__readyState = 'done'; var e = new _IDBVersionChangeEvent2.default('success', { oldVersion: version, newVersion: null }); req.dispatchEvent(e); } function databaseDeleted() { sysdbFinishedCbDelete(false, function () { if (useDatabaseCache && name in websqlDBCache) { delete websqlDBCache[name]; // New calls will treat as though never existed } delete me.__connections[name]; completeDatabaseDelete(); }); } sysdb.readTransaction(function (sysReadTx) { sysReadTx.executeSql('SELECT "version" FROM dbVersions WHERE "name" = ?', [sqlSafeName], function (sysReadTx, data) { if (data.rows.length === 0) { completeDatabaseDelete(); return; } version = data.rows.item(0).version; var openConnections = me.__connections[name] || []; triggerAnyVersionChangeAndBlockedEvents(openConnections, req, version, null).then(function () { // Since we need two databases which can't be in a single transaction, we // do this deleting from `dbVersions` first since the `__sys__` deleting // only impacts file memory whereas this one is critical for avoiding it // being found via `open` or `webkitGetDatabaseNames`; however, we will // avoid committing anyways until all deletions are made and rollback the // `dbVersions` change if they fail sysdb.transaction(function (systx) { systx.executeSql('DELETE FROM dbVersions WHERE "name" = ? ', [sqlSafeName], function () { // Todo: We should also check whether `dbVersions` is empty and if so, delete upon // `deleteDatabaseFiles` config. We also ought to do this when aborting (see // above code with `DELETE FROM dbVersions`) cleanupDatabaseResources(me.__openDatabase, name, escapedDatabaseName, databaseDeleted, dbError); }, dbError); }, dbError, null, function (currentTask, err, done, rollback, commit) { if (currentTask.readOnly || err) { return true; } sysdbFinishedCbDelete = function sysdbFinishedCbDelete(err, cb) { if (err) { rollback(err, cb); } else { commit(cb); } }; return false; }); }, dbError); }, dbError); }); }, dbError); }); return req; }; /** * Compares two keys * @param key1 * @param key2 * @returns {number} */ function cmp(first, second) { var encodedKey1 = Key.encode(first); var encodedKey2 = Key.encode(second); var result = encodedKey1 > encodedKey2 ? 1 : encodedKey1 === encodedKey2 ? 0 : -1; if (_CFG2.default.DEBUG) { // verify that the keys encoded correctly var decodedKey1 = Key.decode(encodedKey1); var decodedKey2 = Key.decode(encodedKey2); if ((typeof first === 'undefined' ? 'undefined' : _typeof(first)) === 'object') { first = JSON.stringify(first); decodedKey1 = JSON.stringify(decodedKey1); } if ((typeof second === 'undefined' ? 'undefined' : _typeof(second)) === 'object') { second = JSON.stringify(second); decodedKey2 = JSON.stringify(decodedKey2); } // encoding/decoding mismatches are usually due to a loss of floating-point precision if (decodedKey1 !== first) { console.warn(first + ' was incorrectly encoded as ' + decodedKey1); } if (decodedKey2 !== second) { console.warn(second + ' was incorrectly encoded as ' + decodedKey2); } } return result; } IDBFactory.prototype.cmp = function (key1, key2) { if (!(this instanceof IDBFactory)) { throw new TypeError('Illegal invocation'); } if (arguments.length < 2) { throw new TypeError('You must provide two keys to be compared'); } // We use encoding facilities already built for proper sorting; // the following "conversions" are for validation only Key.convertValueToKeyRethrowingAndIfInvalid(key1); Key.convertValueToKeyRethrowingAndIfInvalid(key2); return cmp(key1, key2); }; /** * NON-STANDARD!! (Also may return outdated information if a database has since been deleted) * @link https://www.w3.org/Bugs/Public/show_bug.cgi?id=16137 * @link http://lists.w3.org/Archives/Public/public-webapps/2011JulSep/1537.html */ IDBFactory.prototype.webkitGetDatabaseNames = function () { var me = this; if (!(me instanceof IDBFactory)) { throw new TypeError('Illegal invocation'); } if (hasNullOrigin()) { throw (0, _DOMException.createDOMException)('SecurityError', 'Cannot get IndexedDB database names from an opaque origin.'); } var calledDbCreateError = false; function dbGetDatabaseNamesError(tx, err) { if (calledDbCreateError) { return; } err = err ? (0, _DOMException.webSQLErrback)(err) : tx; calledDbCreateError = true; // Re: why bubbling here (and how cancelable is only really relevant for `window.onerror`) see: https://github.com/w3c/IndexedDB/issues/86 var evt = (0, _Event.createEvent)('error', err, { bubbles: true, cancelable: true }); // http://stackoverflow.com/questions/40165909/to-where-do-idbopendbrequest-error-events-bubble-up/40181108#40181108 req.__readyState = 'done'; req.__error = err; req.__result = undefined; req.dispatchEvent(evt); } var req = _IDBRequest.IDBRequest.__createInstance(); createSysDB(me.__openDatabase, function () { sysdb.readTransaction(function (sysReadTx) { sysReadTx.executeSql('SELECT "name" FROM dbVersions', [], function (sysReadTx, data) { var dbNames = _DOMStringList2.default.__createInstance(); for (var i = 0; i < data.rows.length; i++) { dbNames.push(util.unescapeSQLiteResponse(data.rows.item(i).name)); } req.__result = dbNames; req.__readyState = 'done'; var e = (0, _Event.createEvent)('success'); // http://stackoverflow.com/questions/40165909/to-where-do-idbopendbrequest-error-events-bubble-up/40181108#40181108 req.dispatchEvent(e); }, dbGetDatabaseNamesError); }, dbGetDatabaseNamesError); }, dbGetDatabaseNamesError); return req; }; /** * @Todo __forceClose: Test * This is provided to facilitate unit-testing of the * closing of a database connection with a forced flag: * <http://w3c.github.io/IndexedDB/#steps-for-closing-a-database-connection> */ IDBFactory.prototype.__forceClose = function (dbName, connIdx, msg) { var me = this; function forceClose(conn) { conn.__forceClose(msg); } if (dbName == null) { Object.values(me.__connections).forEach(function (conn) { return conn.forEach(forceClose); }); } else if (!me.__connections[dbName]) { console.log('No database connections with that name to force close'); } else if (connIdx == null) { me.__connections[dbName].forEach(forceClose); } else if (!Number.isInteger(connIdx) || connIdx < 0 || connIdx > me.__connections[dbName].length - 1) { throw new TypeError('If providing an argument, __forceClose must be called with a ' + 'numeric index to indicate a specific connection to lose'); } else { forceClose(me.__connections[dbName][connIdx]); } }; IDBFactory.prototype.__setConnectionQueueOrigin = function () { var origin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getOrigin(); connectionQueue[origin] = {}; }; IDBFactory.prototype[Symbol.toStringTag] = 'IDBFactoryPrototype'; Object.defineProperty(IDBFactory, 'prototype', { writable: false }); var shimIndexedDB = IDBFactory.__createInstance(); exports.IDBFactory = IDBFactory; exports.cmp = cmp; exports.shimIndexedDB = shimIndexedDB; }).call(this,require('_process')) },{"./CFG":327,"./DOMException":328,"./DOMStringList":329,"./Event":330,"./IDBDatabase":332,"./IDBRequest":337,"./IDBTransaction":338,"./IDBVersionChangeEvent":339,"./Key":340,"./util":345,"_process":300,"fs":3,"path":299,"sync-promise":302}],334:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.IDBIndex = exports.executeFetchIndexData = exports.buildFetchIndexDataSQL = undefined; var _DOMException = require('./DOMException'); var _IDBCursor = require('./IDBCursor'); var _util = require('./util'); var util = _interopRequireWildcard(_util); var _Key = require('./Key'); var Key = _interopRequireWildcard(_Key); var _IDBKeyRange = require('./IDBKeyRange'); var _IDBTransaction = require('./IDBTransaction'); var _IDBTransaction2 = _interopRequireDefault(_IDBTransaction); var _Sca = require('./Sca'); var Sca = _interopRequireWildcard(_Sca); var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); var _IDBObjectStore = require('./IDBObjectStore'); var _IDBObjectStore2 = _interopRequireDefault(_IDBObjectStore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var readonlyProperties = ['objectStore', 'keyPath', 'multiEntry', 'unique']; /** * IDB Index * http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex * @param {IDBObjectStore} store * @param {IDBIndexProperties} indexProperties * @constructor */ function IDBIndex() { throw new TypeError('Illegal constructor'); } var IDBIndexAlias = IDBIndex; IDBIndex.__createInstance = function (store, indexProperties) { function IDBIndex() { var me = this; me[Symbol.toStringTag] = 'IDBIndex'; util.defineReadonlyProperties(me, readonlyProperties); me.__objectStore = store; me.__name = me.__originalName = indexProperties.columnName; me.__keyPath = Array.isArray(indexProperties.keyPath) ? indexProperties.keyPath.slice() : indexProperties.keyPath; var optionalParams = indexProperties.optionalParams; me.__multiEntry = !!(optionalParams && optionalParams.multiEntry); me.__unique = !!(optionalParams && optionalParams.unique); me.__deleted = !!indexProperties.__deleted; me.__objectStore.__cursors = indexProperties.cursors || []; Object.defineProperty(me, '__currentName', { get: function get() { return '__pendingName' in me ? me.__pendingName : me.name; } }); Object.defineProperty(me, 'name', { enumerable: false, configurable: false, get: function get() { return this.__name; }, set: function set(newName) { var me = this; newName = util.convertToDOMString(newName); var oldName = me.name; _IDBTransaction2.default.__assertVersionChange(me.objectStore.transaction); _IDBTransaction2.default.__assertActive(me.objectStore.transaction); IDBIndexAlias.__invalidStateIfDeleted(me); _IDBObjectStore2.default.__invalidStateIfDeleted(me); if (newName === oldName) { return; } if (me.objectStore.__indexes[newName] && !me.objectStore.__indexes[newName].__deleted && !me.objectStore.__indexes[newName].__pendingDelete) { throw (0, _DOMException.createDOMException)('ConstraintError', 'Index "' + newName + '" already exists on ' + me.objectStore.__currentName); } me.__name = newName; var objectStore = me.objectStore; delete objectStore.__indexes[oldName]; objectStore.__indexes[newName] = me; objectStore.indexNames.splice(objectStore.indexNames.indexOf(oldName), 1, newName); var storeHandle = objectStore.transaction.__storeHandles[objectStore.name]; var oldIndexHandle = storeHandle.__indexHandles[oldName]; oldIndexHandle.__name = newName; // Fix old references storeHandle.__indexHandles[newName] = oldIndexHandle; // Ensure new reference accessible me.__pendingName = oldName; var colInfoToPreserveArr = [['key', 'BLOB ' + (objectStore.autoIncrement ? 'UNIQUE, inc INTEGER PRIMARY KEY AUTOINCREMENT' : 'PRIMARY KEY')], ['value', 'BLOB']].concat(Array.from(objectStore.indexNames).filter(function (indexName) { return indexName !== newName; }).map(function (indexName) { return [util.escapeIndexNameForSQL(indexName), 'BLOB']; })); me.__renameIndex(objectStore, oldName, newName, colInfoToPreserveArr, function (tx, success) { IDBIndexAlias.__updateIndexList(store, tx, function (store) { delete storeHandle.__pendingName; success(store); }); }); } }); } IDBIndex.prototype = IDBIndexAlias.prototype; return new IDBIndex(); }; IDBIndex.__invalidStateIfDeleted = function (index, msg) { if (index.__deleted || index.__pendingDelete || index.__pendingCreate && index.objectStore.transaction && index.objectStore.transaction.__errored) { throw (0, _DOMException.createDOMException)('InvalidStateError', msg || 'This index has been deleted'); } }; /** * Clones an IDBIndex instance for a different IDBObjectStore instance. * @param {IDBIndex} index * @param {IDBObjectStore} store * @protected */ IDBIndex.__clone = function (index, store) { var idx = IDBIndex.__createInstance(store, { columnName: index.name, keyPath: index.keyPath, optionalParams: { multiEntry: index.multiEntry, unique: index.unique } }); ['__pendingCreate', '__pendingDelete', '__deleted', '__originalName', '__recreated'].forEach(function (p) { idx[p] = index[p]; }); return idx; }; /** * Creates a new index on an object store. * @param {IDBObjectStore} store * @param {IDBIndex} index * @returns {IDBIndex} * @protected */ IDBIndex.__createIndex = function (store, index) { var indexName = index.name; var storeName = store.__currentName; var idx = store.__indexes[indexName]; index.__pendingCreate = true; // Add the index to the IDBObjectStore store.indexNames.push(indexName); store.__indexes[indexName] = index; // We add to indexes as needs to be available, e.g., if there is a subsequent deleteIndex call var indexHandle = store.__indexHandles[indexName]; if (!indexHandle || index.__pendingDelete || index.__deleted || indexHandle.__pendingDelete || indexHandle.__deleted) { indexHandle = store.__indexHandles[indexName] = IDBIndex.__clone(index, store); } // Create the index in WebSQL var transaction = store.transaction; transaction.__addNonRequestToTransactionQueue(function createIndex(tx, args, success, failure) { var columnExists = idx && (idx.__deleted || idx.__recreated); // This check must occur here rather than earlier as properties may not have been set yet otherwise var indexValues = {}; function error(tx, err) { failure((0, _DOMException.createDOMException)('UnknownError', 'Could not create index "' + indexName + '"' + err.code + '::' + err.message, err)); } function applyIndex(tx) { // Update the object store's index list IDBIndex.__updateIndexList(store, tx, function () { // Add index entries for all existing records tx.executeSql('SELECT "key", "value" FROM ' + util.escapeStoreNameForSQL(storeName), [], function (tx, data) { _CFG2.default.DEBUG && console.log('Adding existing ' + storeName + ' records to the ' + indexName + ' index'); addIndexEntry(0); function addIndexEntry(i) { if (i < data.rows.length) { try { var value = Sca.decode(util.unescapeSQLiteResponse(data.rows.item(i).value)); var indexKey = Key.extractKeyValueDecodedFromValueUsingKeyPath(value, index.keyPath, index.multiEntry); // Todo: Do we need this stricter error checking? if (indexKey.invalid || indexKey.failure) { // Todo: Do we need invalid checks and should we instead treat these as being duplicates? throw new Error('Go to catch; ignore bad indexKey'); } indexKey = Key.encode(indexKey.value, index.multiEntry); if (index.unique) { if (indexValues[indexKey]) { indexValues = {}; failure((0, _DOMException.createDOMException)('ConstraintError', 'Duplicate values already exist within the store')); return; } indexValues[indexKey] = true; } tx.executeSql('UPDATE ' + util.escapeStoreNameForSQL(storeName) + ' SET ' + util.escapeIndexNameForSQL(indexName) + ' = ? WHERE "key" = ?', [util.escapeSQLiteStatement(indexKey), data.rows.item(i).key], function (tx, data) { addIndexEntry(i + 1); }, error); } catch (e) { // Not a valid value to insert into index, so just continue addIndexEntry(i + 1); } } else { delete index.__pendingCreate; delete indexHandle.__pendingCreate; if (index.__deleted) { delete index.__deleted; delete indexHandle.__deleted; index.__recreated = true; indexHandle.__recreated = true; } indexValues = {}; success(store); } } }, error); }, error); } if (columnExists) { // For a previously existing index, just update the index entries in the existing column applyIndex(tx); } else { // For a new index, add a new column to the object store, then apply the index var sql = ['ALTER TABLE', util.escapeStoreNameForSQL(storeName), 'ADD', util.escapeIndexNameForSQL(index.name), 'BLOB'].join(' '); _CFG2.default.DEBUG && console.log(sql); tx.executeSql(sql, [], applyIndex, error); } }, undefined, store); }; /** * Deletes an index from an object store. * @param {IDBObjectStore} store * @param {IDBIndex} index * @protected */ IDBIndex.__deleteIndex = function (store, index) { // Remove the index from the IDBObjectStore index.__pendingDelete = true; var indexHandle = store.__indexHandles[index.name]; if (indexHandle) { indexHandle.__pendingDelete = true; } store.indexNames.splice(store.indexNames.indexOf(index.name), 1); // Remove the index in WebSQL var transaction = store.transaction; transaction.__addNonRequestToTransactionQueue(function deleteIndex(tx, args, success, failure) { function error(tx, err) { failure((0, _DOMException.createDOMException)('UnknownError', 'Could not delete index "' + index.name + '"', err)); } // Update the object store's index list IDBIndex.__updateIndexList(store, tx, function (store) { delete index.__pendingDelete; delete index.__recreated; index.__deleted = true; if (indexHandle) { indexHandle.__deleted = true; delete indexHandle.__pendingDelete; } success(store); }, error); }, undefined, store); }; /** * Updates index list for the given object store. * @param {IDBObjectStore} store * @param {object} tx * @param {function} success * @param {function} failure */ IDBIndex.__updateIndexList = function (store, tx, success, failure) { var indexList = {}; for (var i = 0; i < store.indexNames.length; i++) { var idx = store.__indexes[store.indexNames[i]]; /** @type {IDBIndexProperties} **/ indexList[idx.name] = { columnName: idx.name, keyPath: idx.keyPath, optionalParams: { unique: idx.unique, multiEntry: idx.multiEntry }, deleted: !!idx.deleted }; } _CFG2.default.DEBUG && console.log('Updating the index list for ' + store.__currentName, indexList); tx.executeSql('UPDATE __sys__ SET "indexList" = ? WHERE "name" = ?', [JSON.stringify(indexList), util.escapeSQLiteStatement(store.__currentName)], function () { success(store); }, failure); }; /** * Retrieves index data for the given key * @param {*|IDBKeyRange} range * @param {string} opType * @param {boolean} nullDisallowed * @param {number} count * @returns {IDBRequest} * @private */ IDBIndex.prototype.__fetchIndexData = function (range, opType, nullDisallowed, count) { var me = this; if (count !== undefined) { count = util.enforceRange(count, 'unsigned long'); } IDBIndex.__invalidStateIfDeleted(me); _IDBObjectStore2.default.__invalidStateIfDeleted(me.objectStore); if (me.objectStore.__deleted) { throw (0, _DOMException.createDOMException)('InvalidStateError', "This index's object store has been deleted"); } _IDBTransaction2.default.__assertActive(me.objectStore.transaction); if (nullDisallowed && range == null) { throw (0, _DOMException.createDOMException)('DataError', 'No key or range was specified'); } var fetchArgs = buildFetchIndexDataSQL(nullDisallowed, me, range, opType, false); return me.objectStore.transaction.__addToTransactionQueue(function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } executeFetchIndexData.apply(undefined, [count].concat(_toConsumableArray(fetchArgs), args)); }, undefined, me); }; /** * Opens a cursor over the given key range. * @param {*|IDBKeyRange} query * @param {string} direction * @returns {IDBRequest} */ IDBIndex.prototype.openCursor = function () /* query, direction */{ var me = this; var _arguments = Array.prototype.slice.call(arguments), query = _arguments[0], direction = _arguments[1]; var cursor = _IDBCursor.IDBCursorWithValue.__createInstance(query, direction, me.objectStore, me, util.escapeIndexNameForSQLKeyColumn(me.name), 'value'); me.__objectStore.__cursors.push(cursor); return cursor.__req; }; /** * Opens a cursor over the given key range. The cursor only includes key values, not data. * @param {*|IDBKeyRange} query * @param {string} direction * @returns {IDBRequest} */ IDBIndex.prototype.openKeyCursor = function () /* query, direction */{ var me = this; var _arguments2 = Array.prototype.slice.call(arguments), query = _arguments2[0], direction = _arguments2[1]; var cursor = _IDBCursor.IDBCursor.__createInstance(query, direction, me.objectStore, me, util.escapeIndexNameForSQLKeyColumn(me.name), 'key'); me.__objectStore.__cursors.push(cursor); return cursor.__req; }; IDBIndex.prototype.get = function (query) { if (!arguments.length) { // Per https://heycam.github.io/webidl/ throw new TypeError('A parameter was missing for `IDBIndex.get`.'); } return this.__fetchIndexData(query, 'value', true); }; IDBIndex.prototype.getKey = function (query) { if (!arguments.length) { // Per https://heycam.github.io/webidl/ throw new TypeError('A parameter was missing for `IDBIndex.getKey`.'); } return this.__fetchIndexData(query, 'key', true); }; IDBIndex.prototype.getAll = function () /* query, count */{ var _arguments3 = Array.prototype.slice.call(arguments), query = _arguments3[0], count = _arguments3[1]; return this.__fetchIndexData(query, 'value', false, count); }; IDBIndex.prototype.getAllKeys = function () /* query, count */{ var _arguments4 = Array.prototype.slice.call(arguments), query = _arguments4[0], count = _arguments4[1]; return this.__fetchIndexData(query, 'key', false, count); }; IDBIndex.prototype.count = function () /* query */{ var me = this; var query = arguments[0]; // With the exception of needing to check whether the index has been // deleted, we could, for greater spec parity (if not accuracy), // just call: // `return me.__objectStore.count(query);` if (util.instanceOf(query, _IDBKeyRange.IDBKeyRange)) { // Todo: Do we need this block? // We don't need to add to cursors array since has the count parameter which won't cache return _IDBCursor.IDBCursorWithValue.__createInstance(query, 'next', me.objectStore, me, util.escapeIndexNameForSQLKeyColumn(me.name), 'value', true).__req; } return me.__fetchIndexData(query, 'count', false); }; IDBIndex.prototype.__renameIndex = function (store, oldName, newName) { var colInfoToPreserveArr = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; var cb = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; var newNameType = 'BLOB'; var storeName = store.__currentName; var escapedStoreNameSQL = util.escapeStoreNameForSQL(storeName); var escapedTmpStoreNameSQL = util.escapeStoreNameForSQL('tmp_' + storeName); var colNamesToPreserve = colInfoToPreserveArr.map(function (colInfo) { return colInfo[0]; }); var colInfoToPreserve = colInfoToPreserveArr.map(function (colInfo) { return colInfo.join(' '); }); var listColInfoToPreserve = colInfoToPreserve.length ? colInfoToPreserve.join(', ') + ', ' : ''; var listColsToPreserve = colNamesToPreserve.length ? colNamesToPreserve.join(', ') + ', ' : ''; // We could adapt the approach at http://stackoverflow.com/a/8430746/271577 // to make the approach reusable without passing column names, but it is a bit fragile store.transaction.__addNonRequestToTransactionQueue(function renameIndex(tx, args, success, error) { var sql = 'ALTER TABLE ' + escapedStoreNameSQL + ' RENAME TO ' + escapedTmpStoreNameSQL; tx.executeSql(sql, [], function (tx, data) { var sql = 'CREATE TABLE ' + escapedStoreNameSQL + '(' + listColInfoToPreserve + util.escapeIndexNameForSQL(newName) + ' ' + newNameType + ')'; tx.executeSql(sql, [], function (tx, data) { var sql = 'INSERT INTO ' + escapedStoreNameSQL + '(' + listColsToPreserve + util.escapeIndexNameForSQL(newName) + ') SELECT ' + listColsToPreserve + util.escapeIndexNameForSQL(oldName) + ' FROM ' + escapedTmpStoreNameSQL; tx.executeSql(sql, [], function (tx, data) { var sql = 'DROP TABLE ' + escapedTmpStoreNameSQL; tx.executeSql(sql, [], function (tx, data) { if (cb) { cb(tx, success); return; } success(); }, function (tx, err) { error(err); }); }, function (tx, err) { error(err); }); }); }, function (tx, err) { error(err); }); }); }; Object.defineProperty(IDBIndex, Symbol.hasInstance, { value: function value(obj) { return util.isObj(obj) && typeof obj.openCursor === 'function' && typeof obj.multiEntry === 'boolean'; } }); readonlyProperties.forEach(function (prop) { Object.defineProperty(IDBIndex.prototype, prop, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); }); Object.defineProperty(IDBIndex.prototype, 'name', { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); }, set: function set(val) { throw new TypeError('Illegal invocation'); } }); IDBIndex.prototype[Symbol.toStringTag] = 'IDBIndexPrototype'; Object.defineProperty(IDBIndex, 'prototype', { writable: false }); function executeFetchIndexData(count, unboundedDisallowed, index, hasKey, range, opType, multiChecks, sql, sqlValues, tx, args, success, error) { if (unboundedDisallowed) { count = 1; } if (count) { sql.push('LIMIT', count); } var isCount = opType === 'count'; _CFG2.default.DEBUG && console.log('Trying to fetch data for Index', sql.join(' '), sqlValues); tx.executeSql(sql.join(' '), sqlValues, function (tx, data) { var records = []; var recordCount = 0; var decode = isCount ? function () {} : opType === 'key' ? function (record) { // Key.convertValueToKey(record.key); // Already validated before storage return Key.decode(util.unescapeSQLiteResponse(record.key)); } : function (record) { // when opType is value return Sca.decode(util.unescapeSQLiteResponse(record.value)); }; if (index.multiEntry) { var escapedIndexNameForKeyCol = util.escapeIndexNameForSQLKeyColumn(index.name); var encodedKey = Key.encode(range, index.multiEntry); var _loop = function _loop(i) { var row = data.rows.item(i); var rowKey = Key.decode(row[escapedIndexNameForKeyCol]); var record = void 0; if (hasKey && (multiChecks && range.some(function (check) { return rowKey.includes(check); }) || // More precise than our SQL Key.isMultiEntryMatch(encodedKey, row[escapedIndexNameForKeyCol]))) { recordCount++; record = row; } else if (!hasKey && !multiChecks) { if (rowKey !== undefined) { recordCount += Array.isArray(rowKey) ? rowKey.length : 1; record = row; } } if (record) { records.push(decode(record)); if (unboundedDisallowed) { return 'break'; } } }; for (var i = 0; i < data.rows.length; i++) { var _ret = _loop(i); if (_ret === 'break') break; } } else { for (var i = 0; i < data.rows.length; i++) { var _record = data.rows.item(i); if (_record) { records.push(decode(_record)); } } recordCount = records.length; } if (isCount) { success(recordCount); } else if (recordCount === 0) { success(unboundedDisallowed ? undefined : []); } else { success(unboundedDisallowed ? records[0] : records); } }, error); } function buildFetchIndexDataSQL(nullDisallowed, index, range, opType, multiChecks) { var hasRange = nullDisallowed || range != null; var col = opType === 'count' ? 'key' : opType; // It doesn't matter which column we use for 'count' as long as it is valid var sql = ['SELECT', util.sqlQuote(col) + (index.multiEntry ? ', ' + util.escapeIndexNameForSQL(index.name) : ''), 'FROM', util.escapeStoreNameForSQL(index.objectStore.__currentName), 'WHERE', util.escapeIndexNameForSQL(index.name), 'NOT NULL']; var sqlValues = []; if (hasRange) { if (multiChecks) { sql.push('AND ('); range.forEach(function (innerKey, i) { if (i > 0) sql.push('OR'); sql.push(util.escapeIndexNameForSQL(index.name), "LIKE ? ESCAPE '^' "); sqlValues.push('%' + util.sqlLIKEEscape(Key.encode(innerKey, index.multiEntry)) + '%'); }); sql.push(')'); } else if (index.multiEntry) { sql.push('AND', util.escapeIndexNameForSQL(index.name), "LIKE ? ESCAPE '^'"); sqlValues.push('%' + util.sqlLIKEEscape(Key.encode(range, index.multiEntry)) + '%'); } else { var convertedRange = (0, _IDBKeyRange.convertValueToKeyRange)(range, nullDisallowed); (0, _IDBKeyRange.setSQLForKeyRange)(convertedRange, util.escapeIndexNameForSQL(index.name), sql, sqlValues, true, false); } } return [nullDisallowed, index, hasRange, range, opType, multiChecks, sql, sqlValues]; } exports.buildFetchIndexDataSQL = buildFetchIndexDataSQL; exports.executeFetchIndexData = executeFetchIndexData; exports.IDBIndex = IDBIndex; exports.default = IDBIndex; },{"./CFG":327,"./DOMException":328,"./IDBCursor":331,"./IDBKeyRange":335,"./IDBObjectStore":336,"./IDBTransaction":338,"./Key":340,"./Sca":341,"./util":345}],335:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.convertValueToKeyRange = exports.IDBKeyRange = exports.setSQLForKeyRange = undefined; var _DOMException = require('./DOMException'); var _Key = require('./Key'); var Key = _interopRequireWildcard(_Key); var _util = require('./util'); var util = _interopRequireWildcard(_util); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var readonlyProperties = ['lower', 'upper', 'lowerOpen', 'upperOpen']; /** * The IndexedDB KeyRange object * http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#dfn-key-range * @param {Object} lower * @param {Object} upper * @param {Object} lowerOpen * @param {Object} upperOpen */ function IDBKeyRange() { throw new TypeError('Illegal constructor'); } var IDBKeyRangeAlias = IDBKeyRange; IDBKeyRange.__createInstance = function (lower, upper, lowerOpen, upperOpen) { function IDBKeyRange() { this[Symbol.toStringTag] = 'IDBKeyRange'; if (lower === undefined && upper === undefined) { throw (0, _DOMException.createDOMException)('DataError', 'Both arguments to the key range method cannot be undefined'); } var lowerConverted = void 0, upperConverted = void 0; if (lower !== undefined) { lowerConverted = Key.roundTrip(lower); // Todo: does this make the "conversions" redundant Key.convertValueToKeyRethrowingAndIfInvalid(lower); } if (upper !== undefined) { upperConverted = Key.roundTrip(upper); // Todo: does this make the "conversions" redundant Key.convertValueToKeyRethrowingAndIfInvalid(upper); } if (lower !== undefined && upper !== undefined && lower !== upper) { if (Key.encode(lower) > Key.encode(upper)) { throw (0, _DOMException.createDOMException)('DataError', '`lower` must not be greater than `upper` argument in `bound()` call.'); } } this.__lower = lowerConverted; this.__upper = upperConverted; this.__lowerOpen = !!lowerOpen; this.__upperOpen = !!upperOpen; } IDBKeyRange.prototype = IDBKeyRangeAlias.prototype; return new IDBKeyRange(); }; IDBKeyRange.prototype.includes = function (key) { // We can't do a regular instanceof check as it will create a loop given our hasInstance implementation if (!util.isObj(this) || typeof this.__lowerOpen !== 'boolean') { throw new TypeError('Illegal invocation'); } if (!arguments.length) { throw new TypeError('IDBKeyRange.includes requires a key argument'); } Key.convertValueToKeyRethrowingAndIfInvalid(key); return Key.isKeyInRange(key, this); }; IDBKeyRange.only = function (value) { if (!arguments.length) { throw new TypeError('IDBKeyRange.only requires a value argument'); } return IDBKeyRange.__createInstance(value, value, false, false); }; IDBKeyRange.lowerBound = function (value /*, open */) { if (!arguments.length) { throw new TypeError('IDBKeyRange.lowerBound requires a value argument'); } return IDBKeyRange.__createInstance(value, undefined, arguments[1], true); }; IDBKeyRange.upperBound = function (value /*, open */) { if (!arguments.length) { throw new TypeError('IDBKeyRange.upperBound requires a value argument'); } return IDBKeyRange.__createInstance(undefined, value, true, arguments[1]); }; IDBKeyRange.bound = function (lower, upper /* , lowerOpen, upperOpen */) { if (arguments.length <= 1) { throw new TypeError('IDBKeyRange.bound requires lower and upper arguments'); } return IDBKeyRange.__createInstance(lower, upper, arguments[2], arguments[3]); }; IDBKeyRange.prototype[Symbol.toStringTag] = 'IDBKeyRangePrototype'; readonlyProperties.forEach(function (prop) { Object.defineProperty(IDBKeyRange.prototype, '__' + prop, { enumerable: false, configurable: false, writable: true }); Object.defineProperty(IDBKeyRange.prototype, prop, { enumerable: true, configurable: true, get: function get() { // We can't do a regular instanceof check as it will create a loop given our hasInstance implementation if (!util.isObj(this) || typeof this.__lowerOpen !== 'boolean') { throw new TypeError('Illegal invocation'); } return this['__' + prop]; } }); }); Object.defineProperty(IDBKeyRange, Symbol.hasInstance, { value: function value(obj) { return util.isObj(obj) && 'upper' in obj && typeof obj.lowerOpen === 'boolean'; } }); Object.defineProperty(IDBKeyRange, 'prototype', { writable: false }); function setSQLForKeyRange(range, quotedKeyColumnName, sql, sqlValues, addAnd, checkCached) { if (range && (range.lower !== undefined || range.upper !== undefined)) { if (addAnd) sql.push('AND'); var encodedLowerKey = void 0, encodedUpperKey = void 0; var hasLower = range.lower !== undefined; var hasUpper = range.upper !== undefined; if (hasLower) { encodedLowerKey = checkCached ? range.__lowerCached : Key.encode(range.lower); } if (hasUpper) { encodedUpperKey = checkCached ? range.__upperCached : Key.encode(range.upper); } if (hasLower) { sqlValues.push(util.escapeSQLiteStatement(encodedLowerKey)); if (hasUpper && encodedLowerKey === encodedUpperKey && !range.lowerOpen && !range.upperOpen) { sql.push(quotedKeyColumnName, '=', '?'); return; } sql.push(quotedKeyColumnName, range.lowerOpen ? '>' : '>=', '?'); } hasLower && hasUpper && sql.push('AND'); if (hasUpper) { sql.push(quotedKeyColumnName, range.upperOpen ? '<' : '<=', '?'); sqlValues.push(util.escapeSQLiteStatement(encodedUpperKey)); } } } function convertValueToKeyRange(value, nullDisallowed) { if (util.instanceOf(value, IDBKeyRange)) { // We still need to validate IDBKeyRange-like objects (the above check is based on loose duck-typing) if (!value.toString() !== '[object IDBKeyRange]') { return IDBKeyRange.__createInstance(value.lower, value.upper, value.lowerOpen, value.upperOpen); } return value; } if (value == null) { if (nullDisallowed) { throw (0, _DOMException.createDOMException)('DataError', 'No key or range was specified'); } return undefined; // Represents unbounded } Key.convertValueToKeyRethrowingAndIfInvalid(value); return IDBKeyRange.only(value); } exports.setSQLForKeyRange = setSQLForKeyRange; exports.IDBKeyRange = IDBKeyRange; exports.convertValueToKeyRange = convertValueToKeyRange; exports.default = IDBKeyRange; },{"./DOMException":328,"./Key":340,"./util":345}],336:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _DOMException = require('./DOMException'); var _IDBCursor = require('./IDBCursor'); var _IDBKeyRange = require('./IDBKeyRange'); var _DOMStringList = require('./DOMStringList'); var _DOMStringList2 = _interopRequireDefault(_DOMStringList); var _util = require('./util'); var util = _interopRequireWildcard(_util); var _Key = require('./Key'); var Key = _interopRequireWildcard(_Key); var _IDBIndex = require('./IDBIndex'); var _IDBTransaction = require('./IDBTransaction'); var _IDBTransaction2 = _interopRequireDefault(_IDBTransaction); var _Sca = require('./Sca'); var Sca = _interopRequireWildcard(_Sca); var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); var _syncPromise = require('sync-promise'); var _syncPromise2 = _interopRequireDefault(_syncPromise); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var readonlyProperties = ['keyPath', 'indexNames', 'transaction', 'autoIncrement']; /** * IndexedDB Object Store * http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBObjectStore * @param {IDBObjectStoreProperties} storeProperties * @param {IDBTransaction} transaction * @constructor */ function IDBObjectStore() { throw new TypeError('Illegal constructor'); } var IDBObjectStoreAlias = IDBObjectStore; IDBObjectStore.__createInstance = function (storeProperties, transaction) { function IDBObjectStore() { var me = this; me[Symbol.toStringTag] = 'IDBObjectStore'; util.defineReadonlyProperties(this, readonlyProperties); me.__name = me.__originalName = storeProperties.name; me.__keyPath = Array.isArray(storeProperties.keyPath) ? storeProperties.keyPath.slice() : storeProperties.keyPath; me.__transaction = transaction; me.__idbdb = storeProperties.idbdb; me.__cursors = storeProperties.cursors || []; // autoInc is numeric (0/1) on WinPhone me.__autoIncrement = !!storeProperties.autoInc; me.__indexes = {}; me.__indexHandles = {}; me.__indexNames = _DOMStringList2.default.__createInstance(); var indexList = storeProperties.indexList; for (var indexName in indexList) { if (indexList.hasOwnProperty(indexName)) { var index = _IDBIndex.IDBIndex.__createInstance(me, indexList[indexName]); me.__indexes[index.name] = index; if (!index.__deleted) { me.indexNames.push(index.name); } } } me.__oldIndexNames = me.indexNames.clone(); Object.defineProperty(this, '__currentName', { get: function get() { return '__pendingName' in this ? this.__pendingName : this.name; } }); Object.defineProperty(this, 'name', { enumerable: false, configurable: false, get: function get() { return this.__name; }, set: function set(name) { var me = this; name = util.convertToDOMString(name); var oldName = me.name; IDBObjectStoreAlias.__invalidStateIfDeleted(me); _IDBTransaction2.default.__assertVersionChange(me.transaction); _IDBTransaction2.default.__assertActive(me.transaction); if (oldName === name) { return; } if (me.__idbdb.__objectStores[name] && !me.__idbdb.__objectStores[name].__pendingDelete) { throw (0, _DOMException.createDOMException)('ConstraintError', 'Object store "' + name + '" already exists in ' + me.__idbdb.name); } me.__name = name; var oldStore = me.__idbdb.__objectStores[oldName]; oldStore.__name = name; // Fix old references me.__idbdb.__objectStores[name] = oldStore; // Ensure new reference accessible delete me.__idbdb.__objectStores[oldName]; // Ensure won't be found me.__idbdb.objectStoreNames.splice(me.__idbdb.objectStoreNames.indexOf(oldName), 1, name); var oldHandle = me.transaction.__storeHandles[oldName]; oldHandle.__name = name; // Fix old references me.transaction.__storeHandles[name] = oldHandle; // Ensure new reference accessible me.__pendingName = oldName; var sql = 'UPDATE __sys__ SET "name" = ? WHERE "name" = ?'; var sqlValues = [util.escapeSQLiteStatement(name), util.escapeSQLiteStatement(oldName)]; _CFG2.default.DEBUG && console.log(sql, sqlValues); me.transaction.__addNonRequestToTransactionQueue(function objectStoreClear(tx, args, success, error) { tx.executeSql(sql, sqlValues, function (tx, data) { var sql = 'ALTER TABLE ' + util.escapeStoreNameForSQL(oldName) + ' RENAME TO ' + util.escapeStoreNameForSQL(name); _CFG2.default.DEBUG && console.log(sql); tx.executeSql(sql, [], function (tx, data) { delete me.__pendingName; success(); }); }, function (tx, err) { error(err); }); }); } }); } IDBObjectStore.prototype = IDBObjectStoreAlias.prototype; return new IDBObjectStore(); }; /** * Clones an IDBObjectStore instance for a different IDBTransaction instance. * @param {IDBObjectStore} store * @param {IDBTransaction} transaction * @protected */ IDBObjectStore.__clone = function (store, transaction) { var newStore = IDBObjectStore.__createInstance({ name: store.__currentName, keyPath: Array.isArray(store.keyPath) ? store.keyPath.slice() : store.keyPath, autoInc: store.autoIncrement, indexList: {}, idbdb: store.__idbdb, cursors: store.__cursors }, transaction); ['__indexes', '__indexNames', '__oldIndexNames', '__deleted', '__pendingDelete', '__pendingCreate', '__originalName'].forEach(function (p) { newStore[p] = store[p]; }); return newStore; }; IDBObjectStore.__invalidStateIfDeleted = function (store, msg) { if (store.__deleted || store.__pendingDelete || store.__pendingCreate && store.transaction && store.transaction.__errored) { throw (0, _DOMException.createDOMException)('InvalidStateError', msg || 'This store has been deleted'); } }; /** * Creates a new object store in the database. * @param {IDBDatabase} db * @param {IDBObjectStore} store * @protected */ IDBObjectStore.__createObjectStore = function (db, store) { // Add the object store to the IDBDatabase var storeName = store.__currentName; store.__pendingCreate = true; db.__objectStores[storeName] = store; db.objectStoreNames.push(storeName); // Add the object store to WebSQL var transaction = db.__versionTransaction; _IDBTransaction2.default.__assertVersionChange(transaction); var storeHandles = transaction.__storeHandles; if (!storeHandles[storeName] || storeHandles[storeName].__pendingDelete || storeHandles[storeName].__deleted) { // The latter conditions are to allow store // recreation to create new clone object storeHandles[storeName] = IDBObjectStore.__clone(store, transaction); } transaction.__addNonRequestToTransactionQueue(function createObjectStore(tx, args, success, failure) { function error(tx, err) { _CFG2.default.DEBUG && console.log(err); failure((0, _DOMException.createDOMException)('UnknownError', 'Could not create object store "' + storeName + '"', err)); } // key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE var sql = ['CREATE TABLE', util.escapeStoreNameForSQL(storeName), '(key BLOB', store.autoIncrement ? 'UNIQUE, inc INTEGER PRIMARY KEY AUTOINCREMENT' : 'PRIMARY KEY', ', value BLOB)'].join(' '); _CFG2.default.DEBUG && console.log(sql); tx.executeSql(sql, [], function (tx, data) { Sca.encode(store.keyPath, function (encodedKeyPath) { tx.executeSql('INSERT INTO __sys__ VALUES (?,?,?,?,?)', [util.escapeSQLiteStatement(storeName), encodedKeyPath, store.autoIncrement, '{}', 1], function () { delete store.__pendingCreate; delete store.__deleted; success(store); }, error); }); }, error); }); return storeHandles[storeName]; }; /** * Deletes an object store from the database. * @param {IDBDatabase} db * @param {IDBObjectStore} store * @protected */ IDBObjectStore.__deleteObjectStore = function (db, store) { // Remove the object store from the IDBDatabase store.__pendingDelete = true; // We don't delete the other index holders in case need reversion store.__indexNames = _DOMStringList2.default.__createInstance(); db.objectStoreNames.splice(db.objectStoreNames.indexOf(store.__currentName), 1); var storeHandle = db.__versionTransaction.__storeHandles[store.__currentName]; if (storeHandle) { storeHandle.__indexNames = _DOMStringList2.default.__createInstance(); storeHandle.__pendingDelete = true; } // Remove the object store from WebSQL var transaction = db.__versionTransaction; _IDBTransaction2.default.__assertVersionChange(transaction); transaction.__addNonRequestToTransactionQueue(function deleteObjectStore(tx, args, success, failure) { function error(tx, err) { _CFG2.default.DEBUG && console.log(err); failure((0, _DOMException.createDOMException)('UnknownError', 'Could not delete ObjectStore', err)); } tx.executeSql('SELECT "name" FROM __sys__ WHERE "name" = ?', [util.escapeSQLiteStatement(store.__currentName)], function (tx, data) { if (data.rows.length > 0) { tx.executeSql('DROP TABLE ' + util.escapeStoreNameForSQL(store.__currentName), [], function () { tx.executeSql('DELETE FROM __sys__ WHERE "name" = ?', [util.escapeSQLiteStatement(store.__currentName)], function () { delete store.__pendingDelete; store.__deleted = true; if (storeHandle) { delete storeHandle.__pendingDelete; storeHandle.__deleted = true; } success(); }, error); }, error); } }); }); }; // Todo: Although we may end up needing to do cloning genuinely asynchronously (for Blobs and FileLists), // and we'll want to ensure the queue starts up synchronously, we nevertheless do the cloning // before entering the queue and its callback since the encoding we do is preceded by validation // which we must do synchronously anyways. If we reimplement Blobs and FileLists asynchronously, // we can detect these types (though validating synchronously as possible) and once entering the // queue callback, ensure they load before triggering success or failure (perhaps by returning and // a `SyncPromise` from the `Sca.clone` operation and later detecting and ensuring it is resolved // before continuing). /** * Determines whether the given inline or out-of-line key is valid, according to the object store's schema. * @param {*} value Used for inline keys * @param {*} key Used for out-of-line keys * @private */ IDBObjectStore.prototype.__validateKeyAndValueAndCloneValue = function (value, key, cursorUpdate) { var me = this; if (me.keyPath !== null) { if (key !== undefined) { throw (0, _DOMException.createDOMException)('DataError', 'The object store uses in-line keys and the key parameter was provided', me); } // Todo Binary: Avoid blobs loading async to ensure cloning (and errors therein) // occurs sync; then can make cloning and this method without callbacks (except where ok // to be async) var _clonedValue = Sca.clone(value); key = Key.extractKeyValueDecodedFromValueUsingKeyPath(_clonedValue, me.keyPath); // May throw so "rethrow" if (key.invalid) { throw (0, _DOMException.createDOMException)('DataError', 'KeyPath was specified, but key was invalid.'); } if (key.failure) { if (!cursorUpdate) { if (!me.autoIncrement) { throw (0, _DOMException.createDOMException)('DataError', 'Could not evaluate a key from keyPath and there is no key generator'); } if (!Key.checkKeyCouldBeInjectedIntoValue(_clonedValue, me.keyPath)) { throw (0, _DOMException.createDOMException)('DataError', 'A key could not be injected into a value'); } // A key will be generated return [undefined, _clonedValue]; } throw (0, _DOMException.createDOMException)('DataError', 'Could not evaluate a key from keyPath'); } // An `IDBCursor.update` call will also throw if not equal to the cursor’s effective key return [key.value, _clonedValue]; } if (key === undefined) { if (!me.autoIncrement) { throw (0, _DOMException.createDOMException)('DataError', 'The object store uses out-of-line keys and has no key generator and the key parameter was not provided.', me); } // A key will be generated key = undefined; } else { Key.convertValueToKeyRethrowingAndIfInvalid(key); } var clonedValue = Sca.clone(value); return [key, clonedValue]; }; /** * From the store properties and object, extracts the value for the key in the object store * If the table has auto increment, get the current number (unless it has a keyPath leading to a * valid but non-numeric or < 1 key) * @param {Object} tx * @param {Object} value * @param {Object} key * @param {function} success * @param {function} failure */ IDBObjectStore.prototype.__deriveKey = function (tx, value, key, success, failCb) { var me = this; // Only run if cloning is needed function keyCloneThenSuccess() { // We want to return the original key, so we don't need to accept an argument here Sca.encode(key, function (key) { key = Sca.decode(key); success(key); }); } if (me.autoIncrement) { // If auto-increment and no valid primaryKey found on the keyPath, get and set the new value, and use if (key === undefined) { Key.generateKeyForStore(tx, me, function (failure, key) { if (failure) { failCb((0, _DOMException.createDOMException)('ConstraintError', 'The key generator\'s current number has reached the maximum safe integer limit')); return; } if (me.keyPath !== null) { // Should not throw now as checked earlier Key.injectKeyIntoValueUsingKeyPath(value, key, me.keyPath); } success(key); }, failCb); } else { Key.possiblyUpdateKeyGenerator(tx, me, key, keyCloneThenSuccess, failCb); } // Not auto-increment } else { keyCloneThenSuccess(); } }; IDBObjectStore.prototype.__insertData = function (tx, encoded, value, clonedKeyOrCurrentNumber, success, error) { var me = this; // The `ConstraintError` to occur for `add` upon a duplicate will occur naturally in attempting an insert // We process the index information first as it will stored in the same table as the store var paramMap = {}; var indexPromises = Object.keys( // We do not iterate `indexNames` as those can be modified synchronously (e.g., // `deleteIndex` could, by its synchronous removal from `indexNames`, prevent // iteration here of an index though per IndexedDB test // `idbobjectstore_createIndex4-deleteIndex-event_order.js`, `createIndex` // should be allowed to first fail even in such a case). me.__indexes).map(function (indexName) { // While this may sometimes resolve sync and sometimes async, the // idea is to avoid, where possible, unnecessary delays (and // consuming code ought to only see a difference in the browser // where we can't control the transaction timeout anyways). return new _syncPromise2.default(function (resolve, reject) { var index = me.__indexes[indexName]; if ( // `createIndex` was called synchronously after the current insertion was added to // the transaction queue so although it was added to `__indexes`, it is not yet // ready to be checked here for the insertion as it will be when running the // `createIndex` operation (e.g., if two items with the same key were added and // *then* a unique index was created, it should not continue to err and abort // yet, as we're still handling the insertions which must be processed (e.g., to // add duplicates which then cause a unique index to fail)) index.__pendingCreate || // If already deleted (and not just slated for deletion (by `__pendingDelete` // after this add), we avoid checks index.__deleted) { resolve(); return; } var indexKey = void 0; try { indexKey = Key.extractKeyValueDecodedFromValueUsingKeyPath(value, index.keyPath, index.multiEntry); // Add as necessary to this and skip past this index if exceptions here) if (indexKey.invalid || indexKey.failure) { throw new Error('Go to catch'); } } catch (err) { resolve(); return; } indexKey = indexKey.value; function setIndexInfo(index) { if (indexKey === undefined) { return; } paramMap[index.__currentName] = Key.encode(indexKey, index.multiEntry); } if (index.unique) { var multiCheck = index.multiEntry && Array.isArray(indexKey); var fetchArgs = (0, _IDBIndex.buildFetchIndexDataSQL)(true, index, indexKey, 'key', multiCheck); _IDBIndex.executeFetchIndexData.apply(undefined, [null].concat(_toConsumableArray(fetchArgs), [tx, null, function success(key) { if (key === undefined) { setIndexInfo(index); resolve(); return; } reject((0, _DOMException.createDOMException)('ConstraintError', 'Index already contains a record equal to ' + (multiCheck ? 'one of the subkeys of' : '') + '`indexKey`')); }, reject])); } else { setIndexInfo(index); resolve(); } }); }); _syncPromise2.default.all(indexPromises).then(function () { var sqlStart = ['INSERT INTO', util.escapeStoreNameForSQL(me.__currentName), '(']; var sqlEnd = [' VALUES (']; var insertSqlValues = []; if (clonedKeyOrCurrentNumber !== undefined) { // Key.convertValueToKey(primaryKey); // Already run sqlStart.push(util.sqlQuote('key'), ','); sqlEnd.push('?,'); insertSqlValues.push(util.escapeSQLiteStatement(Key.encode(clonedKeyOrCurrentNumber))); } for (var key in paramMap) { sqlStart.push(util.escapeIndexNameForSQL(key) + ','); sqlEnd.push('?,'); insertSqlValues.push(util.escapeSQLiteStatement(paramMap[key])); } // removing the trailing comma sqlStart.push(util.sqlQuote('value') + ' )'); sqlEnd.push('?)'); insertSqlValues.push(util.escapeSQLiteStatement(encoded)); var insertSql = sqlStart.join(' ') + sqlEnd.join(' '); _CFG2.default.DEBUG && console.log('SQL for adding', insertSql, insertSqlValues); tx.executeSql(insertSql, insertSqlValues, function (tx, data) { success(clonedKeyOrCurrentNumber); }, function (tx, err) { // Should occur for `add` operation error((0, _DOMException.createDOMException)('ConstraintError', err.message, err)); }); }).catch(function (err) { error(err); }); }; IDBObjectStore.prototype.add = function (value /* , key */) { var me = this; var key = arguments[1]; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No value was specified'); } IDBObjectStore.__invalidStateIfDeleted(me); _IDBTransaction2.default.__assertActive(me.transaction); me.transaction.__assertWritable(); var request = me.transaction.__createRequest(me); var _me$__validateKeyAndV = me.__validateKeyAndValueAndCloneValue(value, key, false), _me$__validateKeyAndV2 = _slicedToArray(_me$__validateKeyAndV, 2), ky = _me$__validateKeyAndV2[0], clonedValue = _me$__validateKeyAndV2[1]; IDBObjectStore.__storingRecordObjectStore(request, me, clonedValue, true, ky); return request; }; IDBObjectStore.prototype.put = function (value /*, key */) { var me = this; var key = arguments[1]; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No value was specified'); } IDBObjectStore.__invalidStateIfDeleted(me); _IDBTransaction2.default.__assertActive(me.transaction); me.transaction.__assertWritable(); var request = me.transaction.__createRequest(me); var _me$__validateKeyAndV3 = me.__validateKeyAndValueAndCloneValue(value, key, false), _me$__validateKeyAndV4 = _slicedToArray(_me$__validateKeyAndV3, 2), ky = _me$__validateKeyAndV4[0], clonedValue = _me$__validateKeyAndV4[1]; IDBObjectStore.__storingRecordObjectStore(request, me, clonedValue, false, ky); return request; }; IDBObjectStore.prototype.__overwrite = function (tx, key, cb, error) { var me = this; // First try to delete if the record exists // Key.convertValueToKey(key); // Already run var sql = 'DELETE FROM ' + util.escapeStoreNameForSQL(me.__currentName) + ' WHERE "key" = ?'; var encodedKey = Key.encode(key); tx.executeSql(sql, [util.escapeSQLiteStatement(encodedKey)], function (tx, data) { _CFG2.default.DEBUG && console.log('Did the row with the', key, 'exist? ', data.rowsAffected); cb(tx); }, function (tx, err) { error(err); }); }; IDBObjectStore.__storingRecordObjectStore = function (request, store, value, noOverwrite /* , key */) { var key = arguments[4]; store.transaction.__pushToQueue(request, function (tx, args, success, error) { store.__deriveKey(tx, value, key, function (clonedKeyOrCurrentNumber) { Sca.encode(value, function (encoded) { function insert(tx) { store.__insertData(tx, encoded, value, clonedKeyOrCurrentNumber, function () { store.__cursors.forEach(function (cursor) { cursor.__invalidateCache(); }); success.apply(undefined, arguments); }, error); } if (!noOverwrite) { store.__overwrite(tx, clonedKeyOrCurrentNumber, insert, error); return; } insert(tx); }); }, error); }); }; IDBObjectStore.prototype.__get = function (query, getKey, getAll, count) { var me = this; if (count !== undefined) { count = util.enforceRange(count, 'unsigned long'); } IDBObjectStore.__invalidStateIfDeleted(me); _IDBTransaction2.default.__assertActive(me.transaction); var range = (0, _IDBKeyRange.convertValueToKeyRange)(query, !getAll); var col = getKey ? 'key' : 'value'; var sql = ['SELECT', util.sqlQuote(col), 'FROM', util.escapeStoreNameForSQL(me.__currentName)]; var sqlValues = []; if (range !== undefined) { sql.push('WHERE'); (0, _IDBKeyRange.setSQLForKeyRange)(range, util.sqlQuote('key'), sql, sqlValues); } if (!getAll) { count = 1; } if (count) { if (typeof count !== 'number' || isNaN(count) || !isFinite(count)) { throw new TypeError('The count parameter must be a finite number'); } sql.push('LIMIT', count); } sql = sql.join(' '); return me.transaction.__addToTransactionQueue(function objectStoreGet(tx, args, success, error) { _CFG2.default.DEBUG && console.log('Fetching', me.__currentName, sqlValues); tx.executeSql(sql, sqlValues, function (tx, data) { _CFG2.default.DEBUG && console.log('Fetched data', data); var ret = void 0; try { // Opera can't deal with the try-catch here. if (data.rows.length === 0) { return getAll ? success([]) : success(); } ret = []; if (getKey) { for (var i = 0; i < data.rows.length; i++) { // Key.convertValueToKey(data.rows.item(i).key); // Already validated before storage ret.push(Key.decode(util.unescapeSQLiteResponse(data.rows.item(i).key), false)); } } else { for (var _i = 0; _i < data.rows.length; _i++) { ret.push(Sca.decode(util.unescapeSQLiteResponse(data.rows.item(_i).value))); } } if (!getAll) { ret = ret[0]; } } catch (e) { // If no result is returned, or error occurs when parsing JSON _CFG2.default.DEBUG && console.log(e); } success(ret); }, function (tx, err) { error(err); }); }, undefined, me); }; IDBObjectStore.prototype.get = function (query) { if (!arguments.length) { throw new TypeError('A parameter was missing for `IDBObjectStore.get`.'); } return this.__get(query); }; IDBObjectStore.prototype.getKey = function (query) { if (!arguments.length) { throw new TypeError('A parameter was missing for `IDBObjectStore.getKey`.'); } return this.__get(query, true); }; IDBObjectStore.prototype.getAll = function () /* query, count */{ if (!arguments.length) { throw new TypeError('A parameter was missing for `IDBObjectStore.getAll`.'); } var _arguments = Array.prototype.slice.call(arguments), query = _arguments[0], count = _arguments[1]; return this.__get(query, false, true, count); }; IDBObjectStore.prototype.getAllKeys = function () /* query, count */{ if (!arguments.length) { throw new TypeError('A parameter was missing for `IDBObjectStore.getAllKeys`.'); } var _arguments2 = Array.prototype.slice.call(arguments), query = _arguments2[0], count = _arguments2[1]; return this.__get(query, true, true, count); }; IDBObjectStore.prototype['delete'] = function (query) { var me = this; if (!(this instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } if (!arguments.length) { throw new TypeError('A parameter was missing for `IDBObjectStore.delete`.'); } IDBObjectStore.__invalidStateIfDeleted(me); _IDBTransaction2.default.__assertActive(me.transaction); me.transaction.__assertWritable(); var range = (0, _IDBKeyRange.convertValueToKeyRange)(query, true); var sqlArr = ['DELETE FROM', util.escapeStoreNameForSQL(me.__currentName), 'WHERE']; var sqlValues = []; (0, _IDBKeyRange.setSQLForKeyRange)(range, util.sqlQuote('key'), sqlArr, sqlValues); var sql = sqlArr.join(' '); return me.transaction.__addToTransactionQueue(function objectStoreDelete(tx, args, success, error) { _CFG2.default.DEBUG && console.log('Deleting', me.__currentName, sqlValues); tx.executeSql(sql, sqlValues, function (tx, data) { _CFG2.default.DEBUG && console.log('Deleted from database', data.rowsAffected); me.__cursors.forEach(function (cursor) { cursor.__invalidateCache(); // Delete }); success(); }, function (tx, err) { error(err); }); }, undefined, me); }; IDBObjectStore.prototype.clear = function () { var me = this; if (!(this instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } IDBObjectStore.__invalidStateIfDeleted(me); _IDBTransaction2.default.__assertActive(me.transaction); me.transaction.__assertWritable(); return me.transaction.__addToTransactionQueue(function objectStoreClear(tx, args, success, error) { tx.executeSql('DELETE FROM ' + util.escapeStoreNameForSQL(me.__currentName), [], function (tx, data) { _CFG2.default.DEBUG && console.log('Cleared all records from database', data.rowsAffected); me.__cursors.forEach(function (cursor) { cursor.__invalidateCache(); // Clear }); success(); }, function (tx, err) { error(err); }); }, undefined, me); }; IDBObjectStore.prototype.count = function () /* query */{ var me = this; var query = arguments[0]; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } IDBObjectStore.__invalidStateIfDeleted(me); _IDBTransaction2.default.__assertActive(me.transaction); // We don't need to add to cursors array since has the count parameter which won't cache return _IDBCursor.IDBCursorWithValue.__createInstance(query, 'next', me, me, 'key', 'value', true).__req; }; IDBObjectStore.prototype.openCursor = function () /* query, direction */{ var me = this; var _arguments3 = Array.prototype.slice.call(arguments), query = _arguments3[0], direction = _arguments3[1]; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } IDBObjectStore.__invalidStateIfDeleted(me); var cursor = _IDBCursor.IDBCursorWithValue.__createInstance(query, direction, me, me, 'key', 'value'); me.__cursors.push(cursor); return cursor.__req; }; IDBObjectStore.prototype.openKeyCursor = function () /* query, direction */{ var me = this; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } IDBObjectStore.__invalidStateIfDeleted(me); var _arguments4 = Array.prototype.slice.call(arguments), query = _arguments4[0], direction = _arguments4[1]; var cursor = _IDBCursor.IDBCursor.__createInstance(query, direction, me, me, 'key', 'key'); me.__cursors.push(cursor); return cursor.__req; }; IDBObjectStore.prototype.index = function (indexName) { var me = this; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No index name was specified'); } IDBObjectStore.__invalidStateIfDeleted(me); _IDBTransaction2.default.__assertNotFinished(me.transaction); var index = me.__indexes[indexName]; if (!index || index.__deleted) { throw (0, _DOMException.createDOMException)('NotFoundError', 'Index "' + indexName + '" does not exist on ' + me.__currentName); } if (!me.__indexHandles[indexName] || me.__indexes[indexName].__pendingDelete || me.__indexes[indexName].__deleted) { me.__indexHandles[indexName] = _IDBIndex.IDBIndex.__clone(index, me); } return me.__indexHandles[indexName]; }; /** * Creates a new index on the object store. * @param {string} indexName * @param {string} keyPath * @param {object} optionalParameters * @returns {IDBIndex} */ IDBObjectStore.prototype.createIndex = function (indexName, keyPath /* , optionalParameters */) { var me = this; var optionalParameters = arguments[2]; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } indexName = String(indexName); // W3C test within IDBObjectStore.js seems to accept string conversion if (arguments.length === 0) { throw new TypeError('No index name was specified'); } if (arguments.length === 1) { throw new TypeError('No key path was specified'); } _IDBTransaction2.default.__assertVersionChange(me.transaction); IDBObjectStore.__invalidStateIfDeleted(me); _IDBTransaction2.default.__assertActive(me.transaction); if (me.__indexes[indexName] && !me.__indexes[indexName].__deleted && !me.__indexes[indexName].__pendingDelete) { throw (0, _DOMException.createDOMException)('ConstraintError', 'Index "' + indexName + '" already exists on ' + me.__currentName); } keyPath = util.convertToSequenceDOMString(keyPath); if (!util.isValidKeyPath(keyPath)) { throw (0, _DOMException.createDOMException)('SyntaxError', 'A valid keyPath must be supplied'); } if (Array.isArray(keyPath) && optionalParameters && optionalParameters.multiEntry) { throw (0, _DOMException.createDOMException)('InvalidAccessError', 'The keyPath argument was an array and the multiEntry option is true.'); } optionalParameters = optionalParameters || {}; /** @name IDBIndexProperties **/ var indexProperties = { columnName: indexName, keyPath: keyPath, optionalParams: { unique: !!optionalParameters.unique, multiEntry: !!optionalParameters.multiEntry } }; var index = _IDBIndex.IDBIndex.__createInstance(me, indexProperties); _IDBIndex.IDBIndex.__createIndex(me, index); return index; }; IDBObjectStore.prototype.deleteIndex = function (name) { var me = this; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No index name was specified'); } _IDBTransaction2.default.__assertVersionChange(me.transaction); IDBObjectStore.__invalidStateIfDeleted(me); _IDBTransaction2.default.__assertActive(me.transaction); var index = me.__indexes[name]; if (!index) { throw (0, _DOMException.createDOMException)('NotFoundError', 'Index "' + name + '" does not exist on ' + me.__currentName); } _IDBIndex.IDBIndex.__deleteIndex(me, index); }; readonlyProperties.forEach(function (prop) { Object.defineProperty(IDBObjectStore.prototype, prop, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); }); Object.defineProperty(IDBObjectStore.prototype, 'name', { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); }, set: function set(val) { throw new TypeError('Illegal invocation'); } }); IDBObjectStore.prototype[Symbol.toStringTag] = 'IDBObjectStorePrototype'; Object.defineProperty(IDBObjectStore, 'prototype', { writable: false }); exports.default = IDBObjectStore; module.exports = exports['default']; },{"./CFG":327,"./DOMException":328,"./DOMStringList":329,"./IDBCursor":331,"./IDBIndex":334,"./IDBKeyRange":335,"./IDBTransaction":338,"./Key":340,"./Sca":341,"./util":345,"sync-promise":302}],337:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.IDBOpenDBRequest = exports.IDBRequest = undefined; var _DOMException = require('./DOMException'); var _eventtarget = require('eventtarget'); var _util = require('./util'); var util = _interopRequireWildcard(_util); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var listeners = ['onsuccess', 'onerror']; var readonlyProperties = ['source', 'transaction', 'readyState']; var doneFlagGetters = ['result', 'error']; /** * The IDBRequest Object that is returns for all async calls * http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#request-api */ function IDBRequest() { throw new TypeError('Illegal constructor'); } IDBRequest.__super = function IDBRequest() { var _this = this; this[Symbol.toStringTag] = 'IDBRequest'; this.__setOptions({ legacyOutputDidListenersThrowFlag: true // Event hook for IndexedB }); doneFlagGetters.forEach(function (prop) { Object.defineProperty(this, '__' + prop, { enumerable: false, configurable: false, writable: true }); Object.defineProperty(this, prop, { enumerable: true, configurable: true, get: function get() { if (this.__readyState !== 'done') { throw (0, _DOMException.createDOMException)('InvalidStateError', "Can't get " + prop + '; the request is still pending.'); } return this['__' + prop]; } }); }, this); util.defineReadonlyProperties(this, readonlyProperties); listeners.forEach(function (listener) { Object.defineProperty(_this, listener, { configurable: true, // Needed by support.js in W3C IndexedDB tests get: function get() { return this['__' + listener]; }, set: function set(val) { this['__' + listener] = val; } }); }, this); listeners.forEach(function (l) { _this[l] = null; }); this.__result = undefined; this.__error = this.__source = this.__transaction = null; this.__readyState = 'pending'; }; IDBRequest.__createInstance = function () { return new IDBRequest.__super(); }; IDBRequest.prototype = _eventtarget.EventTargetFactory.createInstance({ extraProperties: ['debug'] }); IDBRequest.prototype[Symbol.toStringTag] = 'IDBRequestPrototype'; IDBRequest.prototype.__getParent = function () { if (this.toString() === '[object IDBOpenDBRequest]') { return null; } return this.__transaction; }; // Illegal invocations readonlyProperties.forEach(function (prop) { Object.defineProperty(IDBRequest.prototype, prop, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); }); doneFlagGetters.forEach(function (prop) { Object.defineProperty(IDBRequest.prototype, prop, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); }); listeners.forEach(function (listener) { Object.defineProperty(IDBRequest.prototype, listener, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); }, set: function set(val) { throw new TypeError('Illegal invocation'); } }); }); Object.defineProperty(IDBRequest.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBRequest }); IDBRequest.__super.prototype = IDBRequest.prototype; Object.defineProperty(IDBRequest, 'prototype', { writable: false }); var openListeners = ['onblocked', 'onupgradeneeded']; /** * The IDBOpenDBRequest called when a database is opened */ function IDBOpenDBRequest() { throw new TypeError('Illegal constructor'); } IDBOpenDBRequest.prototype = Object.create(IDBRequest.prototype); Object.defineProperty(IDBOpenDBRequest.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBOpenDBRequest }); var IDBOpenDBRequestAlias = IDBOpenDBRequest; IDBOpenDBRequest.__createInstance = function () { function IDBOpenDBRequest() { var _this2 = this; IDBRequest.__super.call(this); this[Symbol.toStringTag] = 'IDBOpenDBRequest'; this.__setOptions({ legacyOutputDidListenersThrowFlag: true, // Event hook for IndexedB extraProperties: ['oldVersion', 'newVersion', 'debug'] }); // Ensure EventTarget preserves our properties openListeners.forEach(function (listener) { Object.defineProperty(_this2, listener, { configurable: true, // Needed by support.js in W3C IndexedDB tests get: function get() { return this['__' + listener]; }, set: function set(val) { this['__' + listener] = val; } }); }, this); openListeners.forEach(function (l) { _this2[l] = null; }); } IDBOpenDBRequest.prototype = IDBOpenDBRequestAlias.prototype; return new IDBOpenDBRequest(); }; openListeners.forEach(function (listener) { Object.defineProperty(IDBOpenDBRequest.prototype, listener, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); }, set: function set(val) { throw new TypeError('Illegal invocation'); } }); }); IDBOpenDBRequest.prototype[Symbol.toStringTag] = 'IDBOpenDBRequestPrototype'; Object.defineProperty(IDBOpenDBRequest, 'prototype', { writable: false }); exports.IDBRequest = IDBRequest; exports.IDBOpenDBRequest = IDBOpenDBRequest; },{"./DOMException":328,"./util":345,"eventtarget":298}],338:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Event = require('./Event'); var _DOMException = require('./DOMException'); var _IDBRequest = require('./IDBRequest'); var _util = require('./util'); var util = _interopRequireWildcard(_util); var _IDBObjectStore = require('./IDBObjectStore'); var _IDBObjectStore2 = _interopRequireDefault(_IDBObjectStore); var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); var _eventtarget = require('eventtarget'); var _syncPromise = require('sync-promise'); var _syncPromise2 = _interopRequireDefault(_syncPromise); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var uniqueID = 0; var listeners = ['onabort', 'oncomplete', 'onerror']; var readonlyProperties = ['objectStoreNames', 'mode', 'db', 'error']; /** * The IndexedDB Transaction * http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBTransaction * @param {IDBDatabase} db * @param {string[]} storeNames * @param {string} mode * @constructor */ function IDBTransaction() { throw new TypeError('Illegal constructor'); } var IDBTransactionAlias = IDBTransaction; IDBTransaction.__createInstance = function (db, storeNames, mode) { function IDBTransaction() { var _this = this; var me = this; me[Symbol.toStringTag] = 'IDBTransaction'; util.defineReadonlyProperties(me, readonlyProperties); me.__id = ++uniqueID; // for debugging simultaneous transactions me.__active = true; me.__running = false; me.__errored = false; me.__requests = []; me.__objectStoreNames = storeNames; me.__mode = mode; me.__db = db; me.__error = null; me.__setOptions({ legacyOutputDidListenersThrowFlag: true // Event hook for IndexedB }); readonlyProperties.forEach(function (readonlyProp) { Object.defineProperty(_this, readonlyProp, { configurable: true }); }); listeners.forEach(function (listener) { Object.defineProperty(_this, listener, { enumerable: true, configurable: true, get: function get() { return this['__' + listener]; }, set: function set(val) { this['__' + listener] = val; } }); }); listeners.forEach(function (l) { _this[l] = null; }); me.__storeHandles = {}; // Kick off the transaction as soon as all synchronous code is done setTimeout(function () { me.__executeRequests(); }, 0); } IDBTransaction.prototype = IDBTransactionAlias.prototype; return new IDBTransaction(); }; IDBTransaction.prototype = _eventtarget.EventTargetFactory.createInstance({ defaultSync: true, extraProperties: ['complete'] }); // Ensure EventTarget preserves our properties IDBTransaction.prototype.__transFinishedCb = function (err, cb) { if (err) { cb(true); // eslint-disable-line standard/no-callback-literal return; } cb(); }; IDBTransaction.prototype.__executeRequests = function () { var me = this; if (me.__running) { _CFG2.default.DEBUG && console.log('Looks like the request set is already running', me.mode); return; } me.__running = true; me.db.__db[me.mode === 'readonly' ? 'readTransaction' : 'transaction']( // `readTransaction` is optimized, at least in `node-websql` function executeRequests(tx) { me.__tx = tx; var q = null, i = -1; function success(result, req) { if (me.__errored || me.__requestsFinished) { // We've already called "onerror", "onabort", or thrown within the transaction, so don't do it again. return; } if (req) { q.req = req; // Need to do this in case of cursors } if (q.req.__readyState === 'done') { // Avoid continuing with aborted requests return; } q.req.__readyState = 'done'; q.req.__result = result; q.req.__error = null; me.__active = true; var e = (0, _Event.createEvent)('success'); q.req.dispatchEvent(e); // Do not set __active flag to false yet: https://github.com/w3c/IndexedDB/issues/87 if (e.__legacyOutputDidListenersThrowError) { (0, _DOMException.logError)('Error', 'An error occurred in a success handler attached to request chain', e.__legacyOutputDidListenersThrowError); // We do nothing else with this error as per spec me.__abortTransaction((0, _DOMException.createDOMException)('AbortError', 'A request was aborted.')); return; } executeNextRequest(); } function error() /* tx, err */{ if (me.__errored || me.__requestsFinished) { // We've already called "onerror", "onabort", or thrown within the transaction, so don't do it again. return; } if (q.req && q.req.__readyState === 'done') { // Avoid continuing with aborted requests return; } for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var err = (0, _DOMException.findError)(args); if (!q.req) { me.__abortTransaction(err); return; } // Fire an error event for the current IDBRequest q.req.__readyState = 'done'; q.req.__error = err; q.req.__result = undefined; q.req.addLateEventListener('error', function (e) { if (e.cancelable && e.defaultPrevented && !e.__legacyOutputDidListenersThrowError) { executeNextRequest(); } }); q.req.addDefaultEventListener('error', function () { me.__abortTransaction(q.req.__error); }); me.__active = true; var e = (0, _Event.createEvent)('error', err, { bubbles: true, cancelable: true }); q.req.dispatchEvent(e); // Do not set __active flag to false yet: https://github.com/w3c/IndexedDB/issues/87 if (e.__legacyOutputDidListenersThrowError) { (0, _DOMException.logError)('Error', 'An error occurred in an error handler attached to request chain', e.__legacyOutputDidListenersThrowError); // We do nothing else with this error as per spec e.preventDefault(); // Prevent 'error' default as steps indicate we should abort with `AbortError` even without cancellation me.__abortTransaction((0, _DOMException.createDOMException)('AbortError', 'A request was aborted.')); } } function executeNextRequest() { if (me.__errored || me.__requestsFinished) { // We've already called "onerror", "onabort", or thrown within the transaction, so don't do it again. return; } i++; if (i >= me.__requests.length) { // All requests in the transaction are done me.__requests = []; if (me.__active) { requestsFinished(); } } else { try { q = me.__requests[i]; if (!q.req) { q.op(tx, q.args, executeNextRequest, error); return; } if (q.req.__readyState === 'done') { // Avoid continuing with aborted requests return; } q.op(tx, q.args, success, error, executeNextRequest); } catch (e) { error(e); } } } executeNextRequest(); }, function webSQLError(webSQLErr) { if (webSQLErr === true) { // Not a genuine SQL error return; } var err = (0, _DOMException.webSQLErrback)(webSQLErr); me.__abortTransaction(err); }, function () { // For Node, we don't need to try running here as we can keep // the transaction running long enough to rollback (in the // next (non-standard) callback for this transaction call) if (me.__transFinishedCb !== IDBTransaction.prototype.__transFinishedCb) { // Node return; } if (!me.__transactionEndCallback && !me.__requestsFinished) { me.__transactionFinished = true; return; } if (me.__transactionEndCallback && !me.__completed) { me.__transFinishedCb(me.__errored, me.__transactionEndCallback); } }, function (currentTask, err, done, rollback, commit) { if (currentTask.readOnly || err) { return true; } me.__transFinishedCb = function (err, cb) { if (err) { rollback(err, cb); } else { commit(cb); } }; if (me.__transactionEndCallback && !me.__completed) { me.__transFinishedCb(me.__errored, me.__transactionEndCallback); } return false; }); function requestsFinished() { me.__active = false; me.__requestsFinished = true; function complete() { me.__completed = true; _CFG2.default.DEBUG && console.log('Transaction completed'); var evt = (0, _Event.createEvent)('complete'); try { me.__internal = true; me.dispatchEvent(evt); me.__internal = false; me.dispatchEvent((0, _Event.createEvent)('__complete')); } catch (e) { me.__internal = false; // An error occurred in the "oncomplete" handler. // It's too late to call "onerror" or "onabort". Throw a global error instead. // (this may seem odd/bad, but it's how all native IndexedDB implementations work) me.__errored = true; throw e; } finally { me.__storeHandles = {}; } } if (me.mode === 'readwrite') { if (me.__transactionFinished) { complete(); return; } me.__transactionEndCallback = complete; return; } if (me.mode === 'readonly') { complete(); return; } var ev = (0, _Event.createEvent)('__beforecomplete'); ev.complete = complete; me.dispatchEvent(ev); } }; /** * Creates a new IDBRequest for the transaction. * NOTE: The transaction is not queued until you call {@link IDBTransaction#__pushToQueue} * @returns {IDBRequest} * @protected */ IDBTransaction.prototype.__createRequest = function (source) { var me = this; var request = _IDBRequest.IDBRequest.__createInstance(); request.__source = source !== undefined ? source : me.db; request.__transaction = me; return request; }; /** * Adds a callback function to the transaction queue * @param {function} callback * @param {*} args * @returns {IDBRequest} * @protected */ IDBTransaction.prototype.__addToTransactionQueue = function (callback, args, source) { var request = this.__createRequest(source); this.__pushToQueue(request, callback, args); return request; }; /** * Adds a callback function to the transaction queue without generating a request * @param {function} callback * @param {*} args * @returns {IDBRequest} * @protected */ IDBTransaction.prototype.__addNonRequestToTransactionQueue = function (callback, args, source) { this.__pushToQueue(null, callback, args); }; /** * Adds an IDBRequest to the transaction queue * @param {IDBRequest} request * @param {function} callback * @param {*} args * @protected */ IDBTransaction.prototype.__pushToQueue = function (request, callback, args) { this.__assertActive(); this.__requests.push({ 'op': callback, 'args': args, 'req': request }); }; IDBTransaction.prototype.__assertActive = function () { if (!this.__active) { throw (0, _DOMException.createDOMException)('TransactionInactiveError', 'A request was placed against a transaction which is currently not active, or which is finished'); } }; IDBTransaction.prototype.__assertWritable = function () { if (this.mode === 'readonly') { throw (0, _DOMException.createDOMException)('ReadOnlyError', 'The transaction is read only'); } }; IDBTransaction.prototype.__assertVersionChange = function () { IDBTransaction.__assertVersionChange(this); }; /** * Returns the specified object store. * @param {string} objectStoreName * @returns {IDBObjectStore} */ IDBTransaction.prototype.objectStore = function (objectStoreName) { var me = this; if (!(me instanceof IDBTransaction)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No object store name was specified'); } IDBTransaction.__assertNotFinished(me); if (me.__objectStoreNames.indexOf(objectStoreName) === -1) { throw (0, _DOMException.createDOMException)('NotFoundError', objectStoreName + ' is not participating in this transaction'); } var store = me.db.__objectStores[objectStoreName]; if (!store) { throw (0, _DOMException.createDOMException)('NotFoundError', objectStoreName + ' does not exist in ' + me.db.name); } if (!me.__storeHandles[objectStoreName] || me.__storeHandles[objectStoreName].__pendingDelete || me.__storeHandles[objectStoreName].__deleted) { // The latter conditions are to allow store // recreation to create new clone object me.__storeHandles[objectStoreName] = _IDBObjectStore2.default.__clone(store, me); } return me.__storeHandles[objectStoreName]; }; IDBTransaction.prototype.__abortTransaction = function (err) { var me = this; (0, _DOMException.logError)('Error', 'An error occurred in a transaction', err); if (me.__errored) { // We've already called "onerror", "onabort", or thrown, so don't do it again. return; } me.__errored = true; if (me.mode === 'versionchange') { // Steps for aborting an upgrade transaction me.db.__version = me.db.__oldVersion; me.db.__objectStoreNames = me.db.__oldObjectStoreNames; me.__objectStoreNames = me.db.__oldObjectStoreNames; Object.values(me.db.__objectStores).concat(Object.values(me.__storeHandles)).forEach(function (store) { if ('__pendingName' in store && me.db.__oldObjectStoreNames.indexOf(store.__pendingName) > -1) { // Store was already created so we restore to name before the rename store.__name = store.__originalName; } store.__indexNames = store.__oldIndexNames; delete store.__pendingDelete; Object.values(store.__indexes).concat(Object.values(store.__indexHandles)).forEach(function (index) { if ('__pendingName' in index && store.__oldIndexNames.indexOf(index.__pendingName) > -1) { // Index was already created so we restore to name before the rename index.__name = index.__originalName; } delete index.__pendingDelete; }); }); } me.__active = false; // Setting here and in requestsFinished for https://github.com/w3c/IndexedDB/issues/87 if (err !== null) { me.__error = err; } if (me.__requestsFinished) { // The transaction has already completed, so we can't call "onerror" or "onabort". // So throw the error instead. setTimeout(function () { throw err; }, 0); } function abort(tx, errOrResult) { if (!tx) { _CFG2.default.DEBUG && console.log('Rollback not possible due to missing transaction', me); } else if (errOrResult && typeof errOrResult.code === 'number') { _CFG2.default.DEBUG && console.log('Rollback erred; feature is probably not supported as per WebSQL', me); } else { _CFG2.default.DEBUG && console.log('Rollback succeeded', me); } me.dispatchEvent((0, _Event.createEvent)('__preabort')); me.__requests.filter(function (q) { return q.req && q.req.__readyState !== 'done'; }).reduce(function (promises, q) { // We reduce to a chain of promises to be queued in order, so we cannot use `Promise.all`, // and I'm unsure whether `setTimeout` currently behaves first-in-first-out with the same timeout // so we could just use a `forEach`. return promises.then(function () { q.req.__readyState = 'done'; q.req.__result = undefined; q.req.__error = (0, _DOMException.createDOMException)('AbortError', 'A request was aborted.'); var reqEvt = (0, _Event.createEvent)('error', q.req.__error, { bubbles: true, cancelable: true }); return new _syncPromise2.default(function (resolve) { setTimeout(function () { q.req.dispatchEvent(reqEvt); // No need to catch errors resolve(); }); }); }); }, _syncPromise2.default.resolve()).then(function () { // Also works when there are no pending requests var evt = (0, _Event.createEvent)('abort', err, { bubbles: true, cancelable: false }); setTimeout(function () { me.__abortFinished = true; me.dispatchEvent(evt); me.__storeHandles = {}; me.dispatchEvent((0, _Event.createEvent)('__abort')); }); }); } me.__transFinishedCb(true, function (rollback) { if (rollback && me.__tx) { // Not supported in standard SQL (and WebSQL errors should // rollback automatically), but for Node.js, etc., we give chance for // manual aborts which would otherwise not work. if (me.mode === 'readwrite') { if (me.__transactionFinished) { abort(); return; } me.__transactionEndCallback = abort; return; } try { me.__tx.executeSql('ROLLBACK', [], abort, abort); // Not working in some circumstances, even in Node } catch (err) { // Browser errs when transaction has ended and since it most likely already erred here, // we call to abort abort(); } } else { abort(null, { code: 0 }); } }); }; IDBTransaction.prototype.abort = function () { var me = this; if (!(me instanceof IDBTransaction)) { throw new TypeError('Illegal invocation'); } _CFG2.default.DEBUG && console.log('The transaction was aborted', me); IDBTransaction.__assertNotFinished(me); me.__abortTransaction(null); }; IDBTransaction.prototype[Symbol.toStringTag] = 'IDBTransactionPrototype'; IDBTransaction.__assertVersionChange = function (tx) { if (!tx || tx.mode !== 'versionchange') { throw (0, _DOMException.createDOMException)('InvalidStateError', 'Not a version transaction'); } }; IDBTransaction.__assertNotVersionChange = function (tx) { if (tx && tx.mode === 'versionchange') { throw (0, _DOMException.createDOMException)('InvalidStateError', 'Cannot be called during a version transaction'); } }; IDBTransaction.__assertNotFinished = function (tx) { if (!tx || tx.__completed || tx.__abortFinished || tx.__errored) { throw (0, _DOMException.createDOMException)('InvalidStateError', 'Transaction finished by commit or abort'); } }; // object store methods behave differently: see https://github.com/w3c/IndexedDB/issues/192 IDBTransaction.__assertNotFinishedObjectStoreMethod = function (tx) { try { IDBTransaction.__assertNotFinished(tx); } catch (err) { if (tx && !tx.__completed && !tx.__abortFinished) { throw (0, _DOMException.createDOMException)('TransactionInactiveError', 'A request was placed against a transaction which is currently not active, or which is finished'); } throw err; } }; IDBTransaction.__assertActive = function (tx) { if (!tx || !tx.__active) { throw (0, _DOMException.createDOMException)('TransactionInactiveError', 'A request was placed against a transaction which is currently not active, or which is finished'); } }; /** * Used by our EventTarget.prototype library to implement bubbling/capturing */ IDBTransaction.prototype.__getParent = function () { return this.db; }; listeners.forEach(function (listener) { Object.defineProperty(IDBTransaction.prototype, listener, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); }, set: function set(val) { throw new TypeError('Illegal invocation'); } }); }); // Illegal invocations readonlyProperties.forEach(function (prop) { Object.defineProperty(IDBTransaction.prototype, prop, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); }); Object.defineProperty(IDBTransaction.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBTransaction }); Object.defineProperty(IDBTransaction, 'prototype', { writable: false }); exports.default = IDBTransaction; module.exports = exports['default']; },{"./CFG":327,"./DOMException":328,"./Event":330,"./IDBObjectStore":336,"./IDBRequest":337,"./util":345,"eventtarget":298,"sync-promise":302}],339:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Event = require('./Event'); var _util = require('./util'); var util = _interopRequireWildcard(_util); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var readonlyProperties = ['oldVersion', 'newVersion']; // Babel apparently having a problem adding `hasInstance` to a class, so we are redefining as a function function IDBVersionChangeEvent(type /* , eventInitDict */) { // eventInitDict is a IDBVersionChangeEventInit (but is not defined as a global) _Event.ShimEvent.call(this, type); this[Symbol.toStringTag] = 'IDBVersionChangeEvent'; this.toString = function () { return '[object IDBVersionChangeEvent]'; }; this.__eventInitDict = arguments[1] || {}; } IDBVersionChangeEvent.prototype = Object.create(_Event.ShimEvent.prototype); IDBVersionChangeEvent.prototype[Symbol.toStringTag] = 'IDBVersionChangeEventPrototype'; readonlyProperties.forEach(function (prop) { Object.defineProperty(IDBVersionChangeEvent.prototype, prop, { enumerable: true, configurable: true, get: function get() { if (!(this instanceof IDBVersionChangeEvent)) { throw new TypeError('Illegal invocation'); } return this.__eventInitDict && this.__eventInitDict[prop] || (prop === 'oldVersion' ? 0 : null); } }); }); Object.defineProperty(IDBVersionChangeEvent, Symbol.hasInstance, { value: function value(obj) { return util.isObj(obj) && 'oldVersion' in obj && typeof obj.defaultPrevented === 'boolean'; } }); Object.defineProperty(IDBVersionChangeEvent.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBVersionChangeEvent }); Object.defineProperty(IDBVersionChangeEvent, 'prototype', { writable: false }); exports.default = IDBVersionChangeEvent; module.exports = exports['default']; },{"./Event":330,"./util":345}],340:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.possiblyUpdateKeyGenerator = exports.generateKeyForStore = exports.findMultiEntryMatches = exports.isKeyInRange = exports.isMultiEntryMatch = exports.checkKeyCouldBeInjectedIntoValue = exports.injectKeyIntoValueUsingKeyPath = exports.extractKeyValueDecodedFromValueUsingKeyPath = exports.evaluateKeyPathOnValue = exports.extractKeyFromValueUsingKeyPath = exports.convertValueToKeyRethrowingAndIfInvalid = exports.convertValueToMultiEntryKey = exports.convertValueToKey = exports.convertValueToMultiEntryKeyDecoded = exports.convertValueToKeyValueDecoded = exports.convertKeyToValue = exports.roundTrip = exports.decode = exports.encode = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _DOMException = require('./DOMException'); var _util = require('./util'); var util = _interopRequireWildcard(_util); var _IDBFactory = require('./IDBFactory'); var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Encodes the keys based on their types. This is required to maintain collations * We leave space for future keys */ var keyTypeToEncodedChar = { invalid: 100, number: 200, date: 300, string: 400, binary: 500, array: 600 }; var keyTypes = Object.keys(keyTypeToEncodedChar); keyTypes.forEach(function (k) { keyTypeToEncodedChar[k] = String.fromCharCode(keyTypeToEncodedChar[k]); }); var encodedCharToKeyType = keyTypes.reduce(function (o, k) { o[keyTypeToEncodedChar[k]] = k; return o; }, {}); /** * The sign values for numbers, ordered from least to greatest. * - "negativeInfinity": Sorts below all other values. * - "bigNegative": Negative values less than or equal to negative one. * - "smallNegative": Negative values between negative one and zero, noninclusive. * - "smallPositive": Positive values between zero and one, including zero but not one. * - "largePositive": Positive values greater than or equal to one. * - "positiveInfinity": Sorts above all other values. */ var signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity']; var types = { invalid: { encode: function encode(key) { return keyTypeToEncodedChar.invalid + '-'; }, decode: function decode(key) { return undefined; } }, // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa // notation. // // sign: takes a value between zero and five, inclusive. Represents infinite cases // and the signs of both the exponent and the fractional part of the number. // exponent: padded to two base-32 digits, represented by the 32's compliment in the // "smallPositive" and "bigNegative" cases to ensure proper lexical sorting. // mantissa: also called the fractional part. Normed 11-digit base-32 representation. // Represented by the 32's compliment in the "smallNegative" and "bigNegative" // cases to ensure proper lexical sorting. number: { // The encode step checks for six numeric cases and generates 14-digit encoded // sign-exponent-mantissa strings. encode: function encode(key) { var key32 = Math.abs(key).toString(32); // Get the index of the decimal. var decimalIndex = key32.indexOf('.'); // Remove the decimal. key32 = decimalIndex !== -1 ? key32.replace('.', '') : key32; // Get the index of the first significant digit. var significantDigitIndex = key32.search(/[^0]/); // Truncate leading zeros. key32 = key32.slice(significantDigitIndex); var sign = void 0, exponent = void 0, mantissa = void 0; // Finite cases: if (isFinite(key)) { // Negative cases: if (key < 0) { // Negative exponent case: if (key > -1) { sign = signValues.indexOf('smallNegative'); exponent = padBase32Exponent(significantDigitIndex); mantissa = flipBase32(padBase32Mantissa(key32)); // Non-negative exponent case: } else { sign = signValues.indexOf('bigNegative'); exponent = flipBase32(padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length)); mantissa = flipBase32(padBase32Mantissa(key32)); } // Non-negative cases: } else { // Negative exponent case: if (key < 1) { sign = signValues.indexOf('smallPositive'); exponent = flipBase32(padBase32Exponent(significantDigitIndex)); mantissa = padBase32Mantissa(key32); // Non-negative exponent case: } else { sign = signValues.indexOf('bigPositive'); exponent = padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length); mantissa = padBase32Mantissa(key32); } } // Infinite cases: } else { exponent = zeros(2); mantissa = zeros(11); sign = signValues.indexOf(key > 0 ? 'positiveInfinity' : 'negativeInfinity'); } return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa; }, // The decode step must interpret the sign, reflip values encoded as the 32's complements, // apply signs to the exponent and mantissa, do the base-32 power operation, and return // the original JavaScript number values. decode: function decode(key) { var sign = +key.substr(2, 1); var exponent = key.substr(3, 2); var mantissa = key.substr(5, 11); switch (signValues[sign]) { case 'negativeInfinity': return -Infinity; case 'positiveInfinity': return Infinity; case 'bigPositive': return pow32(mantissa, exponent); case 'smallPositive': exponent = negate(flipBase32(exponent)); return pow32(mantissa, exponent); case 'smallNegative': exponent = negate(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); case 'bigNegative': exponent = flipBase32(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); default: throw new Error('Invalid number.'); } } }, // Strings are encoded as JSON strings (with quotes and unicode characters escaped). // // If the strings are in an array, then some extra encoding is done to make sorting work correctly: // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON. // To do this, each character of the string is prepended with a dash ("-"), and a space is added to the end of the string. // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared, // the indexes of each string's characters line up with each other. string: { encode: function encode(key, inArray) { if (inArray) { // prepend each character with a dash, and append a space to the end key = key.replace(/(.)/g, '-$1') + ' '; } return keyTypeToEncodedChar.string + '-' + key; }, decode: function decode(key, inArray) { key = key.slice(2); if (inArray) { // remove the space at the end, and the dash before each character key = key.substr(0, key.length - 1).replace(/-(.)/g, '$1'); } return key; } }, // Arrays are encoded as JSON strings. // An extra, value is added to each array during encoding to make empty arrays sort correctly. array: { encode: function encode(key) { var encoded = []; for (var i = 0; i < key.length; i++) { var item = key[i]; var encodedItem = _encode(item, true); // encode the array item encoded[i] = encodedItem; } encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded); }, decode: function decode(key) { var decoded = JSON.parse(key.slice(2)); decoded.pop(); // remove the extra item for (var i = 0; i < decoded.length; i++) { var item = decoded[i]; var decodedItem = _decode(item, true); // decode the item decoded[i] = decodedItem; } return decoded; } }, // Dates are encoded as ISO 8601 strings, in UTC time zone. date: { encode: function encode(key) { return keyTypeToEncodedChar.date + '-' + key.toJSON(); }, decode: function decode(key) { return new Date(key.slice(2)); } }, binary: { // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`) encode: function encode(key) { return keyTypeToEncodedChar.binary + '-' + (key.byteLength ? Array.from(getCopyBytesHeldByBufferSource(key)).map(function (b) { return util.padStart(b, 3, '0'); }) // e.g., '255,005,254,000,001,033' : ''); }, decode: function decode(key) { // Set the entries in buffer's [[ArrayBufferData]] to those in `value` var k = key.slice(2); var arr = k.length ? k.split(',').map(function (s) { return parseInt(s, 10); }) : []; var buffer = new ArrayBuffer(arr.length); var uint8 = new Uint8Array(buffer); uint8.set(arr); return buffer; } } }; /** * Return a padded base-32 exponent value. * @param {number} * @return {string} */ function padBase32Exponent(n) { n = n.toString(32); return n.length === 1 ? '0' + n : n; } /** * Return a padded base-32 mantissa. * @param {string} * @return {string} */ function padBase32Mantissa(s) { return (s + zeros(11)).slice(0, 11); } /** * Flips each digit of a base-32 encoded string. * @param {string} encoded */ function flipBase32(encoded) { var flipped = ''; for (var i = 0; i < encoded.length; i++) { flipped += (31 - parseInt(encoded[i], 32)).toString(32); } return flipped; } /** * Base-32 power function. * RESEARCH: This function does not precisely decode floats because it performs * floating point arithmetic to recover values. But can the original values be * recovered exactly? * Someone may have already figured out a good way to store JavaScript floats as * binary strings and convert back. Barring a better method, however, one route * may be to generate decimal strings that `parseFloat` decodes predictably. * @param {string} * @param {string} * @return {number} */ function pow32(mantissa, exponent) { exponent = parseInt(exponent, 32); if (exponent < 0) { return roundToPrecision(parseInt(mantissa, 32) * Math.pow(32, exponent - 10)); } else { if (exponent < 11) { var whole = mantissa.slice(0, exponent); whole = parseInt(whole, 32); var fraction = mantissa.slice(exponent); fraction = parseInt(fraction, 32) * Math.pow(32, exponent - 11); return roundToPrecision(whole + fraction); } else { var expansion = mantissa + zeros(exponent - 11); return parseInt(expansion, 32); } } } /** * */ function roundToPrecision(num, precision) { precision = precision || 16; return parseFloat(num.toPrecision(precision)); } /** * Returns a string of n zeros. * @param {number} * @return {string} */ function zeros(n) { return '0'.repeat(n); } /** * Negates numeric strings. * @param {string} * @return {string} */ function negate(s) { return '-' + s; } /** * Returns the string "number", "date", "string", "binary", or "array" */ function getKeyType(key) { if (Array.isArray(key)) return 'array'; if (util.isDate(key)) return 'date'; if (util.isBinary(key)) return 'binary'; var keyType = typeof key === 'undefined' ? 'undefined' : _typeof(key); return ['string', 'number'].includes(keyType) ? keyType : 'invalid'; } /** * Keys must be strings, numbers (besides NaN), Dates (if value is not NaN), * binary objects or Arrays * @param input The key input * @param seen An array of already seen keys */ function convertValueToKey(input, seen) { return convertValueToKeyValueDecoded(input, seen, false, true); } /** * Currently not in use */ function convertValueToMultiEntryKey(input) { return convertValueToKeyValueDecoded(input, null, true, true); } // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2 function getCopyBytesHeldByBufferSource(O) { var offset = 0; var length = 0; if (ArrayBuffer.isView(O)) { // Has [[ViewedArrayBuffer]] internal slot var arrayBuffer = O.buffer; if (arrayBuffer === undefined) { throw new TypeError('Could not copy the bytes held by a buffer source as the buffer was undefined.'); } offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached) length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached) } else { length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached) } // const octets = new Uint8Array(input); // const octets = types.binary.decode(types.binary.encode(input)); return new Uint8Array(O.buffer || O, offset, length); } /** * Shortcut utility to avoid returning full keys from `convertValueToKey` * and subsequent need to process in calling code unless `fullKeys` is * set; may throw */ function convertValueToKeyValueDecoded(input, seen, multiEntry, fullKeys) { seen = seen || []; if (seen.includes(input)) return { type: 'array', invalid: true, message: 'An array key cannot be circular' }; var type = getKeyType(input); var ret = { type: type, value: input }; switch (type) { case 'number': { if (Number.isNaN(input)) { return { type: 'NaN', invalid: true }; // List as 'NaN' type for convenience of consumers in reporting errors } return ret; }case 'string': { return ret; }case 'binary': { // May throw (if detached) // Get a copy of the bytes held by the buffer source // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2 var octets = getCopyBytesHeldByBufferSource(input); return { type: 'binary', value: octets }; }case 'array': { // May throw (from binary) var len = input.length; seen.push(input); var keys = []; for (var i = 0; i < len; i++) { // We cannot iterate here with array extras as we must ensure sparse arrays are invalidated if (!multiEntry && !Object.prototype.hasOwnProperty.call(input, i)) { return { type: type, invalid: true, message: 'Does not have own index property' }; } try { var _ret = function () { var entry = input[i]; var key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry if (key.invalid) { if (multiEntry) { return 'continue'; } return { v: { type: type, invalid: true, message: 'Bad array entry value-to-key conversion' } }; } if (!multiEntry || !fullKeys && keys.every(function (k) { return (0, _IDBFactory.cmp)(k, key.value) !== 0; }) || fullKeys && keys.every(function (k) { return (0, _IDBFactory.cmp)(k, key) !== 0; })) { keys.push(fullKeys ? key : key.value); } }(); switch (_ret) { case 'continue': continue; default: if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } } catch (err) { if (!multiEntry) { throw err; } } } return { type: type, value: keys }; }case 'date': { if (!Number.isNaN(input.getTime())) { return fullKeys ? { type: type, value: input.getTime() } : { type: type, value: new Date(input.getTime()) }; } return { type: type, invalid: true, message: 'Not a valid date' }; // Falls through }case 'invalid':default: { // Other `typeof` types which are not valid keys: // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function var _type = input === null ? 'null' : typeof input === 'undefined' ? 'undefined' : _typeof(input); // Convert `null` for convenience of consumers in reporting errors return { type: _type, invalid: true, message: 'Not a valid key; type ' + _type }; } } } function convertValueToMultiEntryKeyDecoded(key, fullKeys) { return convertValueToKeyValueDecoded(key, null, true, fullKeys); } /** * An internal utility */ function convertValueToKeyRethrowingAndIfInvalid(input, seen) { var key = convertValueToKey(input, seen); if (key.invalid) { throw (0, _DOMException.createDOMException)('DataError', key.message || 'Not a valid key; type: ' + key.type); } return key; } function extractKeyFromValueUsingKeyPath(value, keyPath, multiEntry) { return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true); } /** * Not currently in use */ function evaluateKeyPathOnValue(value, keyPath, multiEntry) { return evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, true); } /** * May throw, return `{failure: true}` (e.g., non-object on keyPath resolution) * or `{invalid: true}` (e.g., `NaN`) */ function extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, fullKeys) { var r = evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys); if (r.failure) { return r; } if (!multiEntry) { return convertValueToKeyValueDecoded(r.value, null, false, fullKeys); } return convertValueToMultiEntryKeyDecoded(r.value, fullKeys); } /** * Returns the value of an inline key based on a key path (wrapped in an object with key `value`) * or `{failure: true}` * @param {object} value * @param {string|array} keyPath * @param {boolean} multiEntry * @returns {undefined|array|string} */ function evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys) { if (Array.isArray(keyPath)) { var result = []; return keyPath.some(function (item) { var key = evaluateKeyPathOnValueToDecodedValue(value, item, multiEntry, fullKeys); if (key.failure) { return true; } result.push(key.value); }, []) ? { failure: true } : { value: result }; } if (keyPath === '') { return { value: value }; } var identifiers = keyPath.split('.'); return identifiers.some(function (idntfr, i) { if (idntfr === 'length' && (typeof value === 'string' || Array.isArray(value))) { value = value.length; } else if (util.isBlob(value)) { switch (idntfr) { case 'size':case 'type': value = value[idntfr]; break; } } else if (util.isFile(value)) { switch (idntfr) { case 'name':case 'lastModified': value = value[idntfr]; break; case 'lastModifiedDate': value = new Date(value.lastModified); break; } } else if (!util.isObj(value) || !Object.prototype.hasOwnProperty.call(value, idntfr)) { return true; } else { value = value[idntfr]; return value === undefined; } }) ? { failure: true } : { value: value }; } /** * Sets the inline key value * @param {object} value * @param {*} key * @param {string} keyPath */ function injectKeyIntoValueUsingKeyPath(value, key, keyPath) { var identifiers = keyPath.split('.'); var last = identifiers.pop(); for (var i = 0; i < identifiers.length; i++) { var identifier = identifiers[i]; var hop = Object.prototype.hasOwnProperty.call(value, identifier); if (!hop) { value[identifier] = {}; } value = value[identifier]; } value[last] = key; // key is already a `keyValue` in our processing so no need to convert } // See https://github.com/w3c/IndexedDB/pull/146 function checkKeyCouldBeInjectedIntoValue(value, keyPath) { var identifiers = keyPath.split('.'); identifiers.pop(); for (var i = 0; i < identifiers.length; i++) { if (!util.isObj(value)) { return false; } var identifier = identifiers[i]; var hop = Object.prototype.hasOwnProperty.call(value, identifier); if (!hop) { return true; } value = value[identifier]; } return util.isObj(value); } function isKeyInRange(key, range, checkCached) { var lowerMatch = range.lower === undefined; var upperMatch = range.upper === undefined; var encodedKey = _encode(key, true); var lower = checkCached ? range.__lowerCached : _encode(range.lower, true); var upper = checkCached ? range.__upperCached : _encode(range.upper, true); if (range.lower !== undefined) { if (range.lowerOpen && encodedKey > lower) { lowerMatch = true; } if (!range.lowerOpen && encodedKey >= lower) { lowerMatch = true; } } if (range.upper !== undefined) { if (range.upperOpen && encodedKey < upper) { upperMatch = true; } if (!range.upperOpen && encodedKey <= upper) { upperMatch = true; } } return lowerMatch && upperMatch; } /** * Determines whether an index entry matches a multi-entry key value. * @param {string} encodedEntry The entry value (already encoded) * @param {string} encodedKey The full index key (already encoded) * @returns {boolean} */ function isMultiEntryMatch(encodedEntry, encodedKey) { var keyType = encodedCharToKeyType[encodedKey.slice(0, 1)]; if (keyType === 'array') { return encodedKey.indexOf(encodedEntry) > 1; } else { return encodedKey === encodedEntry; } } function findMultiEntryMatches(keyEntry, range) { var matches = []; if (Array.isArray(keyEntry)) { for (var i = 0; i < keyEntry.length; i++) { var key = keyEntry[i]; if (Array.isArray(key)) { if (range && range.lower === range.upper) { continue; } if (key.length === 1) { key = key[0]; } else { var nested = findMultiEntryMatches(key, range); if (nested.length > 0) { matches.push(key); } continue; } } if (range == null || isKeyInRange(key, range, true)) { matches.push(key); } } } else { if (range == null || isKeyInRange(keyEntry, range, true)) { matches.push(keyEntry); } } return matches; } /** * Not currently in use but keeping for spec parity */ function convertKeyToValue(key) { var type = key.type; var value = key.value; switch (type) { case 'number':case 'string': { return value; }case 'array': { var array = []; var len = value.length; var index = 0; while (index < len) { var entry = convertKeyToValue(value[index]); array[index] = entry; index++; } return array; }case 'date': { return new Date(value); }case 'binary': { var _len = value.length; var buffer = new ArrayBuffer(_len); // Set the entries in buffer's [[ArrayBufferData]] to those in `value` var uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength); uint8.set(value); return buffer; }case 'invalid':default: throw new Error('Bad key'); } } function _encode(key, inArray) { // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation if (key === undefined) { return null; } // array, date, number, string, binary (should already have detected "invalid") return types[getKeyType(key)].encode(key, inArray); } function _decode(key, inArray) { if (typeof key !== 'string') { return undefined; } return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray); } function roundTrip(key, inArray) { return _decode(_encode(key, inArray), inArray); } var MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`) function getCurrentNumber(tx, store, callback, sqlFailCb) { tx.executeSql('SELECT "currNum" FROM __sys__ WHERE "name" = ?', [util.escapeSQLiteStatement(store.__currentName)], function (tx, data) { if (data.rows.length !== 1) { callback(1); // eslint-disable-line standard/no-callback-literal } else { callback(data.rows.item(0).currNum); } }, function (tx, error) { sqlFailCb((0, _DOMException.createDOMException)('DataError', 'Could not get the auto increment value for key', error)); }); } // Bump up the auto-inc counter if the key path-resolved value is valid (greater than old value and >=1) OR // if a manually passed in key is valid (numeric and >= 1) and >= any primaryKey function setCurrentNumber(tx, store, num, successCb, failCb) { var sql = 'UPDATE __sys__ SET "currNum" = ? WHERE "name" = ?'; num = num === MAX_ALLOWED_CURRENT_NUMBER ? num + 2 // Since incrementing by one will have no effect in JavaScript on this unsafe max, we represent the max as a number incremented by two. The getting of the current number is never returned to the user and is only used in safe comparisons, so it is safe for us to represent it in this manner : num + 1; var sqlValues = [num, util.escapeSQLiteStatement(store.__currentName)]; _CFG2.default.DEBUG && console.log(sql, sqlValues); tx.executeSql(sql, sqlValues, function (tx, data) { successCb(num); }, function (tx, err) { failCb((0, _DOMException.createDOMException)('UnknownError', 'Could not set the auto increment value for key', err)); }); } function generateKeyForStore(tx, store, cb, sqlFailCb) { getCurrentNumber(tx, store, function (key) { if (key > MAX_ALLOWED_CURRENT_NUMBER) { // 2 ^ 53 (See <https://github.com/w3c/IndexedDB/issues/147>) return cb('failure'); // eslint-disable-line standard/no-callback-literal } // Increment current number by 1 (we cannot leverage SQLite's // autoincrement (and decrement when not needed), as decrementing // will be overwritten/ignored upon the next insert) setCurrentNumber(tx, store, key, function () { cb(null, key); }, sqlFailCb); }, sqlFailCb); } // Fractional or numbers exceeding the max do not get changed in the result // per https://github.com/w3c/IndexedDB/issues/147 // so we do not return a key function possiblyUpdateKeyGenerator(tx, store, key, successCb, sqlFailCb) { // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers // (or numbers larger than the max) are now to have the explicit effect of // setting the current number (up to the max), so we do not optimize them // out here if (typeof key !== 'number' || key < 1) { // Optimize with no need to get the current number // Auto-increment attempted with a bad key; // we are not to change the current number, but the steps don't call for failure // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1 successCb(); } else { // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher // to determine which to use and whether to update the current number getCurrentNumber(tx, store, function (cn) { var value = Math.floor(Math.min(key, MAX_ALLOWED_CURRENT_NUMBER)); var useNewKeyForAutoInc = value >= cn; if (useNewKeyForAutoInc) { setCurrentNumber(tx, store, value, successCb, sqlFailCb); } else { // Not updated successCb(); } }, sqlFailCb); } } /* eslint-disable object-property-newline */ exports.encode = _encode; exports.decode = _decode; exports.roundTrip = roundTrip; exports.convertKeyToValue = convertKeyToValue; exports.convertValueToKeyValueDecoded = convertValueToKeyValueDecoded; exports.convertValueToMultiEntryKeyDecoded = convertValueToMultiEntryKeyDecoded; exports.convertValueToKey = convertValueToKey; exports.convertValueToMultiEntryKey = convertValueToMultiEntryKey; exports.convertValueToKeyRethrowingAndIfInvalid = convertValueToKeyRethrowingAndIfInvalid; exports.extractKeyFromValueUsingKeyPath = extractKeyFromValueUsingKeyPath; exports.evaluateKeyPathOnValue = evaluateKeyPathOnValue; exports.extractKeyValueDecodedFromValueUsingKeyPath = extractKeyValueDecodedFromValueUsingKeyPath; exports.injectKeyIntoValueUsingKeyPath = injectKeyIntoValueUsingKeyPath; exports.checkKeyCouldBeInjectedIntoValue = checkKeyCouldBeInjectedIntoValue; exports.isMultiEntryMatch = isMultiEntryMatch; exports.isKeyInRange = isKeyInRange; exports.findMultiEntryMatches = findMultiEntryMatches; exports.generateKeyForStore = generateKeyForStore; exports.possiblyUpdateKeyGenerator = possiblyUpdateKeyGenerator; },{"./CFG":327,"./DOMException":328,"./IDBFactory":333,"./util":345}],341:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.clone = exports.decode = exports.encode = undefined; var _typeson = require('typeson'); var _typeson2 = _interopRequireDefault(_typeson); var _structuredCloningThrowing = require('typeson-registry/presets/structured-cloning-throwing'); var _structuredCloningThrowing2 = _interopRequireDefault(_structuredCloningThrowing); var _DOMException = require('./DOMException'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Todo: Register `ImageBitmap` and add `Blob`/`File`/`FileList` // Todo: add a proper polyfill for `ImageData` using node-canvas // See also: http://stackoverflow.com/questions/42170826/categories-for-rejection-by-the-structured-cloning-algorithm var typeson = new _typeson2.default().register(_structuredCloningThrowing2.default); // We are keeping the callback approach for now in case we wish to reexpose Blob, File, FileList // import Blob from 'w3c-blob'; // Needed by Node; uses native if available (browser) function encode(obj, cb) { var ret = void 0; try { ret = typeson.stringifySync(obj); } catch (err) { // SCA in typeson-registry using `DOMException` which is not defined (e.g., in Node) if (_typeson2.default.hasConstructorOf(err, ReferenceError) || // SCA in typeson-registry threw a cloning error and we are in a // supporting environment (e.g., the browser) where `ShimDOMException` is // an alias for `DOMException`; if typeson-registry ever uses our shim // to throw, we can use this condition alone. _typeson2.default.hasConstructorOf(err, _DOMException.ShimDOMException)) { throw (0, _DOMException.createDOMException)('DataCloneError', 'The object cannot be cloned.'); } throw err; // We should rethrow non-cloning exceptions like from // throwing getters (as in the W3C test, key-conversion-exceptions.htm) } if (cb) cb(ret); return ret; } function decode(obj) { return typeson.parse(obj); } function clone(val) { // We don't return the intermediate `encode` as we'll need to reencode the clone as it may differ return decode(encode(val)); } exports.encode = encode; exports.decode = decode; exports.clone = clone; },{"./DOMException":328,"typeson":325,"typeson-registry/presets/structured-cloning-throwing":304}],342:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // ID_Start (includes Other_ID_Start) var UnicodeIDStart = '(?:[$A-Z_a-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2118-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309B-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FD5\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDD40-\\uDD74\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDF00-\\uDF1F\\uDF30-\\uDF4A\\uDF50-\\uDF75\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF\\uDFD1-\\uDFD5]|\\uD801[\\uDC00-\\uDC9D\\uDCB0-\\uDCD3\\uDCD8-\\uDCFB\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC60-\\uDC76\\uDC80-\\uDC9E\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDD00-\\uDD15\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBE\\uDDBF\\uDE00\\uDE10-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE33\\uDE60-\\uDE7C\\uDE80-\\uDE9C\\uDEC0-\\uDEC7\\uDEC9-\\uDEE4\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF60-\\uDF72\\uDF80-\\uDF91]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2]|\\uD804[\\uDC03-\\uDC37\\uDC83-\\uDCAF\\uDCD0-\\uDCE8\\uDD03-\\uDD26\\uDD50-\\uDD72\\uDD76\\uDD83-\\uDDB2\\uDDC1-\\uDDC4\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE2B\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDF00-\\uDF19]|\\uD806[\\uDCA0-\\uDCDF\\uDCFF\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50\\uDF93-\\uDF9F\\uDFE0]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00\\uDC01]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB]|\\uD83A[\\uDC00-\\uDCC4\\uDD00-\\uDD43]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1]|\\uD87E[\\uDC00-\\uDE1D])'; // ID_Continue (includes Other_ID_Continue) var UnicodeIDContinue = '(?:[$0-9A-Z_a-z\\xAA\\xB5\\xB7\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u08A0-\\u08B4\\u08B6-\\u08BD\\u08D4-\\u08E1\\u08E3-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0AF9\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BEF\\u0C00-\\u0C03\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58-\\u0C5A\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C80-\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D01-\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D54-\\u0D57\\u0D5F-\\u0D63\\u0D66-\\u0D6F\\u0D7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1369-\\u1371\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19DA\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1CD0-\\u1CD2\\u1CD4-\\u1CF6\\u1CF8\\u1CF9\\u1D00-\\u1DF5\\u1DFB-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u200C\\u200D\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2118-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FD5\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA8FD\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2F\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDD40-\\uDD74\\uDDFD\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDEE0\\uDF00-\\uDF1F\\uDF30-\\uDF4A\\uDF50-\\uDF7A\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF\\uDFD1-\\uDFD5]|\\uD801[\\uDC00-\\uDC9D\\uDCA0-\\uDCA9\\uDCB0-\\uDCD3\\uDCD8-\\uDCFB\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC60-\\uDC76\\uDC80-\\uDC9E\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDD00-\\uDD15\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBE\\uDDBF\\uDE00-\\uDE03\\uDE05\\uDE06\\uDE0C-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE33\\uDE38-\\uDE3A\\uDE3F\\uDE60-\\uDE7C\\uDE80-\\uDE9C\\uDEC0-\\uDEC7\\uDEC9-\\uDEE6\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF60-\\uDF72\\uDF80-\\uDF91]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2]|\\uD804[\\uDC00-\\uDC46\\uDC66-\\uDC6F\\uDC7F-\\uDCBA\\uDCD0-\\uDCE8\\uDCF0-\\uDCF9\\uDD00-\\uDD34\\uDD36-\\uDD3F\\uDD50-\\uDD73\\uDD76\\uDD80-\\uDDC4\\uDDCA-\\uDDCC\\uDDD0-\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE37\\uDE3E\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEEA\\uDEF0-\\uDEF9\\uDF00-\\uDF03\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3C-\\uDF44\\uDF47\\uDF48\\uDF4B-\\uDF4D\\uDF50\\uDF57\\uDF5D-\\uDF63\\uDF66-\\uDF6C\\uDF70-\\uDF74]|\\uD805[\\uDC00-\\uDC4A\\uDC50-\\uDC59\\uDC80-\\uDCC5\\uDCC7\\uDCD0-\\uDCD9\\uDD80-\\uDDB5\\uDDB8-\\uDDC0\\uDDD8-\\uDDDD\\uDE00-\\uDE40\\uDE44\\uDE50-\\uDE59\\uDE80-\\uDEB7\\uDEC0-\\uDEC9\\uDF00-\\uDF19\\uDF1D-\\uDF2B\\uDF30-\\uDF39]|\\uD806[\\uDCA0-\\uDCE9\\uDCFF\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC36\\uDC38-\\uDC40\\uDC50-\\uDC59\\uDC72-\\uDC8F\\uDC92-\\uDCA7\\uDCA9-\\uDCB6]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE60-\\uDE69\\uDED0-\\uDEED\\uDEF0-\\uDEF4\\uDF00-\\uDF36\\uDF40-\\uDF43\\uDF50-\\uDF59\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50-\\uDF7E\\uDF8F-\\uDF9F\\uDFE0]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00\\uDC01]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99\\uDC9D\\uDC9E]|\\uD834[\\uDD65-\\uDD69\\uDD6D-\\uDD72\\uDD7B-\\uDD82\\uDD85-\\uDD8B\\uDDAA-\\uDDAD\\uDE42-\\uDE44]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB\\uDFCE-\\uDFFF]|\\uD836[\\uDE00-\\uDE36\\uDE3B-\\uDE6C\\uDE75\\uDE84\\uDE9B-\\uDE9F\\uDEA1-\\uDEAF]|\\uD838[\\uDC00-\\uDC06\\uDC08-\\uDC18\\uDC1B-\\uDC21\\uDC23\\uDC24\\uDC26-\\uDC2A]|\\uD83A[\\uDC00-\\uDCC4\\uDCD0-\\uDCD6\\uDD00-\\uDD4A\\uDD50-\\uDD59]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1]|\\uD87E[\\uDC00-\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF])'; exports.UnicodeIDStart = UnicodeIDStart; exports.UnicodeIDContinue = UnicodeIDContinue; },{}],343:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); require('babel-polyfill'); var _UnicodeIdentifiers = require('./UnicodeIdentifiers'); var _setGlobalVars = require('./setGlobalVars'); var _setGlobalVars2 = _interopRequireDefault(_setGlobalVars); var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // BEGIN: Same code as in browser.js /* eslint-env browser, worker */ _CFG2.default.win = typeof window !== 'undefined' ? window : self; // For Web Workers // END: Same code as in browser.js // `Object.assign` including within `EventTarget`, generator functions, `Array.from`, etc.; see https://babeljs.io/docs/usage/polyfill/ _CFG2.default.UnicodeIDStart = _UnicodeIdentifiers.UnicodeIDStart; _CFG2.default.UnicodeIDContinue = _UnicodeIdentifiers.UnicodeIDContinue; exports.default = _setGlobalVars2.default; module.exports = exports['default']; },{"./CFG":327,"./UnicodeIdentifiers":342,"./setGlobalVars":344,"babel-polyfill":1}],344:[function(require,module,exports){ (function (global){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* globals self */ var _IDBVersionChangeEvent = require('./IDBVersionChangeEvent'); var _IDBVersionChangeEvent2 = _interopRequireDefault(_IDBVersionChangeEvent); var _IDBCursor = require('./IDBCursor'); var _IDBRequest = require('./IDBRequest'); var _DOMException = require('./DOMException'); var _IDBFactory = require('./IDBFactory'); var _IDBKeyRange = require('./IDBKeyRange'); var _IDBKeyRange2 = _interopRequireDefault(_IDBKeyRange); var _IDBObjectStore = require('./IDBObjectStore'); var _IDBObjectStore2 = _interopRequireDefault(_IDBObjectStore); var _IDBIndex = require('./IDBIndex'); var _IDBIndex2 = _interopRequireDefault(_IDBIndex); var _IDBTransaction = require('./IDBTransaction'); var _IDBTransaction2 = _interopRequireDefault(_IDBTransaction); var _IDBDatabase = require('./IDBDatabase'); var _IDBDatabase2 = _interopRequireDefault(_IDBDatabase); var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function setConfig(prop, val) { if (prop && (typeof prop === 'undefined' ? 'undefined' : _typeof(prop)) === 'object') { for (var p in prop) { setConfig(p, prop[p]); } return; } if (!(prop in _CFG2.default)) { throw new Error(prop + ' is not a valid configuration property'); } _CFG2.default[prop] = val; } function setGlobalVars(idb, initialConfig) { if (initialConfig) { setConfig(initialConfig); } var IDB = idb || (typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : typeof global !== 'undefined' ? global : {}); function shim(name, value, propDesc) { if (!propDesc || !Object.defineProperty) { try { // Try setting the property. This will fail if the property is read-only. IDB[name] = value; } catch (e) { console.log(e); } } if (IDB[name] !== value && Object.defineProperty) { // Setting a read-only property failed, so try re-defining the property try { var desc = propDesc || {}; if (!('value' in desc)) { desc.get = function () { return value; }; } Object.defineProperty(IDB, name, desc); } catch (e) { // With `indexedDB`, PhantomJS fails here and below but // not above, while Chrome is reverse (and Firefox doesn't // get here since no WebSQL to use for shimming) } } if (IDB[name] !== value) { typeof console !== 'undefined' && console.warn && console.warn('Unable to shim ' + name); } } shim('shimIndexedDB', _IDBFactory.shimIndexedDB, { enumerable: false, configurable: true }); if (IDB.shimIndexedDB) { IDB.shimIndexedDB.__useShim = function () { function setNonIDBGlobals() { var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; shim(prefix + 'DOMException', IDB.indexedDB.modules.ShimDOMException); shim(prefix + 'DOMStringList', IDB.indexedDB.modules.ShimDOMStringList, { enumerable: false, configurable: true, writable: true, value: IDB.indexedDB.modules.ShimDOMStringList }); shim(prefix + 'Event', IDB.indexedDB.modules.ShimEvent, { configurable: true, writable: true, value: IDB.indexedDB.modules.ShimEvent, enumerable: false }); shim(prefix + 'CustomEvent', IDB.indexedDB.modules.ShimCustomEvent, { configurable: true, writable: true, value: IDB.indexedDB.modules.ShimCustomEvent, enumerable: false }); shim(prefix + 'EventTarget', IDB.indexedDB.modules.ShimEventTarget, { configurable: true, writable: true, value: IDB.indexedDB.modules.ShimEventTarget, enumerable: false }); } var shimIDBFactory = IDB.shimIndexedDB.modules.IDBFactory; if (_CFG2.default.win.openDatabase !== undefined) { _IDBFactory.shimIndexedDB.__openDatabase = _CFG2.default.win.openDatabase.bind(_CFG2.default.win); // We cache here in case the function is overwritten later as by the IndexedDB support promises tests // Polyfill ALL of IndexedDB, using WebSQL [['indexedDB', _IDBFactory.shimIndexedDB], ['IDBFactory', shimIDBFactory], ['IDBDatabase', _IDBDatabase2.default], ['IDBObjectStore', _IDBObjectStore2.default], ['IDBIndex', _IDBIndex2.default], ['IDBTransaction', _IDBTransaction2.default], ['IDBCursor', _IDBCursor.IDBCursor], ['IDBCursorWithValue', _IDBCursor.IDBCursorWithValue], ['IDBKeyRange', _IDBKeyRange2.default], ['IDBRequest', _IDBRequest.IDBRequest], ['IDBOpenDBRequest', _IDBRequest.IDBOpenDBRequest], ['IDBVersionChangeEvent', _IDBVersionChangeEvent2.default]].forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), prop = _ref2[0], obj = _ref2[1]; shim(prop, obj, { enumerable: false, configurable: true }); }); if (_CFG2.default.fullIDLSupport) { // Slow per MDN so off by default! Though apparently needed for WebIDL: http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements Object.setPrototypeOf(IDB.IDBOpenDBRequest, IDB.IDBRequest); Object.setPrototypeOf(IDB.IDBCursorWithValue, IDB.IDBCursor); var ShimEvent = IDB.shimIndexedDB.modules.ShimEvent; var ShimEventTarget = IDB.shimIndexedDB.modules.ShimEventTarget; Object.setPrototypeOf(_IDBDatabase2.default, ShimEventTarget); Object.setPrototypeOf(_IDBRequest.IDBRequest, ShimEventTarget); Object.setPrototypeOf(_IDBTransaction2.default, ShimEventTarget); Object.setPrototypeOf(_IDBVersionChangeEvent2.default, ShimEvent); Object.setPrototypeOf(_DOMException.ShimDOMException, Error); Object.setPrototypeOf(_DOMException.ShimDOMException.prototype, Error.prototype); } if (IDB.indexedDB && IDB.indexedDB.modules) { if (_CFG2.default.addNonIDBGlobals) { // As `DOMStringList` exists per IDL (and Chrome) in the global // thread (but not in workers), we prefix the name to avoid // shadowing or conflicts setNonIDBGlobals('Shim'); } if (_CFG2.default.replaceNonIDBGlobals) { setNonIDBGlobals(); } } IDB.shimIndexedDB.__setConnectionQueueOrigin(); } }; IDB.shimIndexedDB.__debug = function (val) { _CFG2.default.DEBUG = val; }; IDB.shimIndexedDB.__setConfig = setConfig; IDB.shimIndexedDB.__getConfig = function (prop) { if (!(prop in _CFG2.default)) { throw new Error(prop + ' is not a valid configuration property'); } return _CFG2.default[prop]; }; IDB.shimIndexedDB.__setUnicodeIdentifiers = function (_ref3) { var UnicodeIDStart = _ref3.UnicodeIDStart, UnicodeIDContinue = _ref3.UnicodeIDContinue; setConfig({ UnicodeIDStart: UnicodeIDStart, UnicodeIDContinue: UnicodeIDContinue }); }; } // Workaround to prevent an error in Firefox if (!('indexedDB' in IDB) && typeof window !== 'undefined') { // 2nd condition avoids problems in Node IDB.indexedDB = IDB.indexedDB || IDB.webkitIndexedDB || IDB.mozIndexedDB || IDB.oIndexedDB || IDB.msIndexedDB; } // Detect browsers with known IndexedDb issues (e.g. Android pre-4.4) var poorIndexedDbSupport = false; if (typeof navigator !== 'undefined' && ( // Ignore Node or other environments // Bad non-Chrome Android support /Android (?:2|3|4\.[0-3])/.test(navigator.userAgent) && !navigator.userAgent.includes('Chrome') || // Bad non-Safari iOS9 support (see <https://github.com/axemclion/IndexedDBShim/issues/252>) (!navigator.userAgent.includes('Safari') || navigator.userAgent.includes('Chrome')) && // Exclude genuine Safari: http://stackoverflow.com/a/7768006/271577 // Detect iOS: http://stackoverflow.com/questions/9038625/detect-if-device-is-ios/9039885#9039885 // and detect version 9: http://stackoverflow.com/a/26363560/271577 /(iPad|iPhone|iPod).* os 9_/i.test(navigator.userAgent) && !window.MSStream // But avoid IE11 )) { poorIndexedDbSupport = true; } if (!_CFG2.default.DEFAULT_DB_SIZE) { _CFG2.default.DEFAULT_DB_SIZE = ( // Safari currently requires larger size: (We don't need a larger size for Node as node-websql doesn't use this info) // https://github.com/axemclion/IndexedDBShim/issues/41 // https://github.com/axemclion/IndexedDBShim/issues/115 typeof navigator !== 'undefined' && navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') ? 25 : 4) * 1024 * 1024; } if ((!IDB.indexedDB || poorIndexedDbSupport) && _CFG2.default.win.openDatabase !== undefined) { IDB.shimIndexedDB.__useShim(); } else { IDB.IDBDatabase = IDB.IDBDatabase || IDB.webkitIDBDatabase; IDB.IDBTransaction = IDB.IDBTransaction || IDB.webkitIDBTransaction || {}; IDB.IDBCursor = IDB.IDBCursor || IDB.webkitIDBCursor; IDB.IDBKeyRange = IDB.IDBKeyRange || IDB.webkitIDBKeyRange; } return IDB; } exports.default = setGlobalVars; module.exports = exports['default']; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./CFG":327,"./DOMException":328,"./IDBCursor":331,"./IDBDatabase":332,"./IDBFactory":333,"./IDBIndex":334,"./IDBKeyRange":335,"./IDBObjectStore":336,"./IDBRequest":337,"./IDBTransaction":338,"./IDBVersionChangeEvent":339}],345:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.padStart = exports.convertToSequenceDOMString = exports.convertToDOMString = exports.enforceRange = exports.isValidKeyPath = exports.defineReadonlyProperties = exports.isIterable = exports.isBinary = exports.isFile = exports.isRegExp = exports.isBlob = exports.isDate = exports.isObj = exports.instanceOf = exports.sqlQuote = exports.sqlLIKEEscape = exports.escapeIndexNameForSQLKeyColumn = exports.escapeIndexNameForSQL = exports.escapeStoreNameForSQL = exports.unescapeDatabaseNameForSQLAndFiles = exports.escapeDatabaseNameForSQLAndFiles = exports.unescapeSQLiteResponse = exports.escapeSQLiteStatement = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _CFG = require('./CFG'); var _CFG2 = _interopRequireDefault(_CFG); var _regex = require('unicode-9.0.0/Binary_Property/Expands_On_NFD/regex'); var _regex2 = _interopRequireDefault(_regex); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function escapeUnmatchedSurrogates(arg) { // http://stackoverflow.com/a/6701665/271577 return arg.replace(/([\uD800-\uDBFF])(?![\uDC00-\uDFFF])|(^|[^\uD800-\uDBFF])([\uDC00-\uDFFF])/g, function (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) { // Could add a corresponding surrogate for compatibility with `node-sqlite3`: http://bugs.python.org/issue12569 and http://stackoverflow.com/a/6701665/271577 // but Chrome having problems if (unmatchedHighSurrogate) { return '^2' + padStart(unmatchedHighSurrogate.charCodeAt().toString(16), 4, '0'); } return (precedingLow || '') + '^3' + padStart(unmatchedLowSurrogate.charCodeAt().toString(16), 4, '0'); }); } function escapeNameForSQLiteIdentifier(arg) { // http://stackoverflow.com/a/6701665/271577 return '_' + // Prevent empty string escapeUnmatchedSurrogates(arg.replace(/\^/g, '^^') // Escape our escape // http://www.sqlite.org/src/tktview?name=57c971fc74 .replace(/\0/g, '^0') // We need to avoid identifiers being treated as duplicates based on SQLite's ASCII-only case-insensitive table and column names // (For SQL in general, however, see http://stackoverflow.com/a/17215009/271577 // See also https://www.sqlite.org/faq.html#q18 re: Unicode (non-ASCII) case-insensitive not working .replace(/([A-Z])/g, '^$1')); } // The escaping of unmatched surrogates was needed by Chrome but not Node function escapeSQLiteStatement(arg) { return escapeUnmatchedSurrogates(arg.replace(/\^/g, '^^').replace(/\0/g, '^0')); } function unescapeSQLiteResponse(arg) { return unescapeUnmatchedSurrogates(arg).replace(/\^0/g, '\0').replace(/\^\^/g, '^'); } function sqlEscape(arg) { // https://www.sqlite.org/lang_keywords.html // http://stackoverflow.com/a/6701665/271577 // There is no need to escape ', `, or [], as // we should always be within double quotes // NUL should have already been stripped return arg.replace(/"/g, '""'); } function sqlQuote(arg) { return '"' + sqlEscape(arg) + '"'; } function escapeDatabaseNameForSQLAndFiles(db) { if (_CFG2.default.escapeDatabaseName) { // We at least ensure NUL is escaped by default, but we need to still // handle empty string and possibly also length (potentially // throwing if too long), escaping casing (including Unicode?), // and escaping special characters depending on file system return _CFG2.default.escapeDatabaseName(escapeSQLiteStatement(db)); } db = 'D' + escapeNameForSQLiteIdentifier(db); if (_CFG2.default.escapeNFDForDatabaseNames !== false) { // ES6 copying of regex with different flags db = db.replace(new RegExp(_regex2.default, 'g'), function (expandable) { return '^4' + padStart(expandable.codePointAt().toString(16), 6, '0'); }); } if (_CFG2.default.databaseCharacterEscapeList !== false) { db = db.replace(_CFG2.default.databaseCharacterEscapeList ? new RegExp(_CFG2.default.databaseCharacterEscapeList, 'g') : /[\u0000-\u001F\u007F"*/:<>?\\|]/g, function (n0) { return '^1' + padStart(n0.charCodeAt().toString(16), 2, '0'); }); } if (_CFG2.default.databaseNameLengthLimit !== false && db.length >= (_CFG2.default.databaseNameLengthLimit || 254) - (_CFG2.default.addSQLiteExtension !== false ? 7 /* '.sqlite'.length */ : 0)) { throw new Error('Unexpectedly long database name supplied; length limit required for Node compatibility; passed length: ' + db.length + '; length limit setting: ' + (_CFG2.default.databaseNameLengthLimit || 254) + '.'); } return db + (_CFG2.default.addSQLiteExtension !== false ? '.sqlite' : ''); // Shouldn't have quoting (do we even need NUL/case escaping here?) } function unescapeUnmatchedSurrogates(arg) { return arg.replace(/(\^+)3(d[0-9a-f]{3})/g, function (_, esc, lowSurr) { return esc.length % 2 ? String.fromCharCode(parseInt(lowSurr, 16)) : _; }).replace(/(\^+)2(d[0-9a-f]{3})/g, function (_, esc, highSurr) { return esc.length % 2 ? String.fromCharCode(parseInt(highSurr, 16)) : _; }); } // Not in use internally but supplied for convenience function unescapeDatabaseNameForSQLAndFiles(db) { if (_CFG2.default.unescapeDatabaseName) { // We at least ensure NUL is unescaped by default, but we need to still // handle empty string and possibly also length (potentially // throwing if too long), unescaping casing (including Unicode?), // and unescaping special characters depending on file system return _CFG2.default.unescapeDatabaseName(unescapeSQLiteResponse(db)); } return unescapeUnmatchedSurrogates(db.slice(2) // D_ // CFG.databaseCharacterEscapeList .replace(/(\^+)1([0-9a-f]{2})/g, function (_, esc, hex) { return esc.length % 2 ? String.fromCharCode(parseInt(hex, 16)) : _; }) // CFG.escapeNFDForDatabaseNames .replace(/(\^+)4([0-9a-f]{6})/g, function (_, esc, hex) { return esc.length % 2 ? String.fromCodePoint(parseInt(hex, 16)) : _; })) // escapeNameForSQLiteIdentifier (including unescapeUnmatchedSurrogates() above) .replace(/(\^+)([A-Z])/g, function (_, esc, upperCase) { return esc.length % 2 ? upperCase : _; }).replace(/(\^+)0/g, function (_, esc) { return esc.length % 2 ? '\0' : _; }).replace(/\^\^/g, '^'); } function escapeStoreNameForSQL(store) { return sqlQuote('S' + escapeNameForSQLiteIdentifier(store)); } function escapeIndexNameForSQL(index) { return sqlQuote('I' + escapeNameForSQLiteIdentifier(index)); } function escapeIndexNameForSQLKeyColumn(index) { return 'I' + escapeNameForSQLiteIdentifier(index); } function sqlLIKEEscape(str) { // https://www.sqlite.org/lang_expr.html#like return sqlEscape(str).replace(/\^/g, '^^'); } // Babel doesn't seem to provide a means of using the `instanceof` operator with Symbol.hasInstance (yet?) function instanceOf(obj, Clss) { return Clss[Symbol.hasInstance](obj); } function isObj(obj) { return obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object'; } function isDate(obj) { return isObj(obj) && typeof obj.getDate === 'function'; } function isBlob(obj) { return isObj(obj) && typeof obj.size === 'number' && typeof obj.slice === 'function' && !('lastModified' in obj); } function isRegExp(obj) { return isObj(obj) && typeof obj.flags === 'string' && typeof obj.exec === 'function'; } function isFile(obj) { return isObj(obj) && typeof obj.name === 'string' && typeof obj.slice === 'function' && 'lastModified' in obj; } function isBinary(obj) { return isObj(obj) && typeof obj.byteLength === 'number' && (typeof obj.slice === 'function' || // `TypedArray` (view on buffer) or `ArrayBuffer` typeof obj.getFloat64 === 'function' // `DataView` (view on buffer) ); } function isIterable(obj) { return isObj(obj) && typeof obj[Symbol.iterator] === 'function'; } function defineReadonlyProperties(obj, props) { props = typeof props === 'string' ? [props] : props; props.forEach(function (prop) { Object.defineProperty(obj, '__' + prop, { enumerable: false, configurable: false, writable: true }); Object.defineProperty(obj, prop, { enumerable: true, configurable: true, get: function get() { return this['__' + prop]; } }); }); } var HexDigit = '[0-9a-fA-F]'; // The commented out line below is technically the grammar, with a SyntaxError // to occur if larger than U+10FFFF, but we will prevent the error by // establishing the limit in regular expressions // const HexDigits = HexDigit + HexDigit + '*'; var HexDigits = '0*(?:' + HexDigit + '{1,5}|10' + HexDigit + '{4})*'; var UnicodeEscapeSequence = '(?:u' + HexDigit + '{4}|u{' + HexDigits + '})'; function isIdentifier(item) { // For load-time and run-time performance, we don't provide the complete regular // expression for identifiers, but these can be passed in, using the expressions // found at https://gist.github.com/brettz9/b4cd6821d990daa023b2e604de371407 // ID_Start (includes Other_ID_Start) var UnicodeIDStart = _CFG2.default.UnicodeIDStart || '[$A-Z_a-z]'; // ID_Continue (includes Other_ID_Continue) var UnicodeIDContinue = _CFG2.default.UnicodeIDContinue || '[$0-9A-Z_a-z]'; var IdentifierStart = '(?:' + UnicodeIDStart + '|[$_]|\\\\' + UnicodeEscapeSequence + ')'; var IdentifierPart = '(?:' + UnicodeIDContinue + '|[$_]|\\\\' + UnicodeEscapeSequence + '|\\u200C|\\u200D)'; return new RegExp('^' + IdentifierStart + IdentifierPart + '*$').test(item); } function isValidKeyPathString(keyPathString) { return typeof keyPathString === 'string' && (keyPathString === '' || isIdentifier(keyPathString) || keyPathString.split('.').every(isIdentifier)); } function isValidKeyPath(keyPath) { return isValidKeyPathString(keyPath) || Array.isArray(keyPath) && keyPath.length && // Convert array from sparse to dense http://www.2ality.com/2012/06/dense-arrays.html Array.apply(null, keyPath).every(function (kpp) { // See also https://heycam.github.io/webidl/#idl-DOMString return isValidKeyPathString(kpp); // Should already be converted to string by here }); } function enforceRange(number, type) { number = Math.floor(Number(number)); var max = void 0, min = void 0; switch (type) { case 'unsigned long long': { max = 0x1FFFFFFFFFFFFF; // 2^53 - 1 min = 0; break; } case 'unsigned long': { max = 0xFFFFFFFF; // 2^32 - 1 min = 0; break; } default: throw new Error('Unrecognized type supplied to enforceRange'); } if (isNaN(number) || !isFinite(number) || number > max || number < min) { throw new TypeError('Invalid range: ' + number); } return number; } function convertToDOMString(v, treatNullAs) { return v === null && treatNullAs ? '' : ToString(v); } function ToString(o) { // Todo: See `es-abstract/es7` return '' + o; // `String()` will not throw with Symbols } function convertToSequenceDOMString(val) { // Per <https://heycam.github.io/webidl/#idl-sequence>, converting to a sequence works with iterables if (isIterable(val)) { // We don't want `Array.from` to convert primitives // Per <https://heycam.github.io/webidl/#es-DOMString>, converting to a `DOMString` to be via `ToString`: https://tc39.github.io/ecma262/#sec-tostring return Array.from(val).map(ToString); } return val; } // Todo: Replace with `String.prototype.padStart` when targeting supporting Node version function padStart(str, ct, fill) { return new Array(ct - String(str).length + 1).join(fill) + str; } exports.escapeSQLiteStatement = escapeSQLiteStatement; exports.unescapeSQLiteResponse = unescapeSQLiteResponse; exports.escapeDatabaseNameForSQLAndFiles = escapeDatabaseNameForSQLAndFiles; exports.unescapeDatabaseNameForSQLAndFiles = unescapeDatabaseNameForSQLAndFiles; exports.escapeStoreNameForSQL = escapeStoreNameForSQL; exports.escapeIndexNameForSQL = escapeIndexNameForSQL; exports.escapeIndexNameForSQLKeyColumn = escapeIndexNameForSQLKeyColumn; exports.sqlLIKEEscape = sqlLIKEEscape; exports.sqlQuote = sqlQuote; exports.instanceOf = instanceOf; exports.isObj = isObj; exports.isDate = isDate; exports.isBlob = isBlob; exports.isRegExp = isRegExp; exports.isFile = isFile; exports.isBinary = isBinary; exports.isIterable = isIterable; exports.defineReadonlyProperties = defineReadonlyProperties; exports.isValidKeyPath = isValidKeyPath; exports.enforceRange = enforceRange; exports.convertToDOMString = convertToDOMString; exports.convertToSequenceDOMString = convertToSequenceDOMString; exports.padStart = padStart; },{"./CFG":327,"unicode-9.0.0/Binary_Property/Expands_On_NFD/regex":326}]},{},[343])(343) }); //# sourceMappingURL=indexeddbshim-noninvasive.js.map
ajax/libs/onsen/1.3.13/js/onsenui.min.js
dhenson02/cdnjs
/*! onsenui - v1.3.13 - 2015-11-10 */ !function(){function getAttributes(element){return Node_get_attributes.call(element)}function setAttribute(element,attribute,value){try{Element_setAttribute.call(element,attribute,value)}catch(e){}}function removeAttribute(element,attribute){Element_removeAttribute.call(element,attribute)}function childNodes(element){return Node_get_childNodes.call(element)}function empty(element){for(;element.childNodes.length;)element.removeChild(element.lastChild)}function insertAdjacentHTML(element,position,html){HTMLElement_insertAdjacentHTMLPropertyDescriptor.value.call(element,position,html)}function inUnsafeMode(){var isUnsafe=!0;try{detectionDiv.innerHTML="<test/>"}catch(ex){isUnsafe=!1}return isUnsafe}function cleanse(html,targetElement){function cleanseAttributes(element){var attributes=getAttributes(element);if(attributes&&attributes.length){for(var events,i=0,len=attributes.length;len>i;i++){var attribute=attributes[i],name=attribute.name;"o"!==name[0]&&"O"!==name[0]||"n"!==name[1]&&"N"!==name[1]||(events=events||[],events.push({name:attribute.name,value:attribute.value}))}if(events)for(var i=0,len=events.length;len>i;i++){var attribute=events[i];removeAttribute(element,attribute.name),setAttribute(element,"x-"+attribute.name,attribute.value)}}for(var children=childNodes(element),i=0,len=children.length;len>i;i++)cleanseAttributes(children[i])}var cleaner=document.implementation.createHTMLDocument("cleaner");empty(cleaner.documentElement),MSApp.execUnsafeLocalFunction(function(){insertAdjacentHTML(cleaner.documentElement,"afterbegin",html)});var scripts=cleaner.documentElement.querySelectorAll("script");Array.prototype.forEach.call(scripts,function(script){switch(script.type.toLowerCase()){case"":script.type="text/inert";break;case"text/javascript":case"text/ecmascript":case"text/x-javascript":case"text/jscript":case"text/livescript":case"text/javascript1.1":case"text/javascript1.2":case"text/javascript1.3":script.type="text/inert-"+script.type.slice("text/".length);break;case"application/javascript":case"application/ecmascript":case"application/x-javascript":script.type="application/inert-"+script.type.slice("application/".length)}}),cleanseAttributes(cleaner.documentElement);var cleanedNodes=[];return"HTML"===targetElement.tagName?cleanedNodes=Array.prototype.slice.call(document.adoptNode(cleaner.documentElement).childNodes):(cleaner.head&&(cleanedNodes=cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.head).childNodes))),cleaner.body&&(cleanedNodes=cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.body).childNodes)))),cleanedNodes}function cleansePropertySetter(property,setter){var propertyDescriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,property),originalSetter=propertyDescriptor.set;Object.defineProperty(HTMLElement.prototype,property,{get:propertyDescriptor.get,set:function(value){if(window.WinJS&&window.WinJS._execUnsafe&&inUnsafeMode())originalSetter.call(this,value);else{var that=this,nodes=cleanse(value,that);MSApp.execUnsafeLocalFunction(function(){setter(propertyDescriptor,that,nodes)})}},enumerable:propertyDescriptor.enumerable,configurable:propertyDescriptor.configurable})}if(window.MSApp&&MSApp.execUnsafeLocalFunction){var Element_setAttribute=Object.getOwnPropertyDescriptor(Element.prototype,"setAttribute").value,Element_removeAttribute=Object.getOwnPropertyDescriptor(Element.prototype,"removeAttribute").value,HTMLElement_insertAdjacentHTMLPropertyDescriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,"insertAdjacentHTML"),Node_get_attributes=Object.getOwnPropertyDescriptor(Node.prototype,"attributes").get,Node_get_childNodes=Object.getOwnPropertyDescriptor(Node.prototype,"childNodes").get,detectionDiv=document.createElement("div");cleansePropertySetter("innerHTML",function(propertyDescriptor,target,elements){empty(target);for(var i=0,len=elements.length;len>i;i++)target.appendChild(elements[i])}),cleansePropertySetter("outerHTML",function(propertyDescriptor,target,elements){for(var i=0,len=elements.length;len>i;i++)target.insertAdjacentElement("afterend",elements[i]);target.parentNode.removeChild(target)})}}(),function(){var initializing=!1,fnTest=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.Class=function(){},Class.extend=function(prop){function Class(){!initializing&&this.init&&this.init.apply(this,arguments)}var _super=this.prototype;initializing=!0;var prototype=new this;initializing=!1;for(var name in prop)prototype[name]="function"==typeof prop[name]&&"function"==typeof _super[name]&&fnTest.test(prop[name])?function(name,fn){return function(){var tmp=this._super;this._super=_super[name];var ret=fn.apply(this,arguments);return this._super=tmp,ret}}(name,prop[name]):prop[name];return Class.prototype=prototype,Class.prototype.constructor=Class,Class.extend=arguments.callee,Class}}(),function(){"use strict";function FastClick(layer,options){function bind(method,context){return function(){return method.apply(context,arguments)}}var oldOnClick;if(options=options||{},this.trackingClick=!1,this.trackingClickStart=0,this.targetElement=null,this.touchStartX=0,this.touchStartY=0,this.lastTouchIdentifier=0,this.touchBoundary=options.touchBoundary||10,this.layer=layer,this.tapDelay=options.tapDelay||200,this.tapTimeout=options.tapTimeout||700,!FastClick.notNeeded(layer)){for(var methods=["onMouse","onClick","onTouchStart","onTouchMove","onTouchEnd","onTouchCancel"],context=this,i=0,l=methods.length;l>i;i++)context[methods[i]]=bind(context[methods[i]],context);deviceIsAndroid&&(layer.addEventListener("mouseover",this.onMouse,!0),layer.addEventListener("mousedown",this.onMouse,!0),layer.addEventListener("mouseup",this.onMouse,!0)),layer.addEventListener("click",this.onClick,!0),layer.addEventListener("touchstart",this.onTouchStart,!1),layer.addEventListener("touchmove",this.onTouchMove,!1),layer.addEventListener("touchend",this.onTouchEnd,!1),layer.addEventListener("touchcancel",this.onTouchCancel,!1),Event.prototype.stopImmediatePropagation||(layer.removeEventListener=function(type,callback,capture){var rmv=Node.prototype.removeEventListener;"click"===type?rmv.call(layer,type,callback.hijacked||callback,capture):rmv.call(layer,type,callback,capture)},layer.addEventListener=function(type,callback,capture){var adv=Node.prototype.addEventListener;"click"===type?adv.call(layer,type,callback.hijacked||(callback.hijacked=function(event){event.propagationStopped||callback(event)}),capture):adv.call(layer,type,callback,capture)}),"function"==typeof layer.onclick&&(oldOnClick=layer.onclick,layer.addEventListener("click",function(event){oldOnClick(event)},!1),layer.onclick=null)}}var deviceIsWindowsPhone=navigator.userAgent.indexOf("Windows Phone")>=0,deviceIsAndroid=navigator.userAgent.indexOf("Android")>0&&!deviceIsWindowsPhone,deviceIsIOS=/iP(ad|hone|od)/.test(navigator.userAgent)&&!deviceIsWindowsPhone,deviceIsIOS4=deviceIsIOS&&/OS 4_\d(_\d)?/.test(navigator.userAgent),deviceIsIOSWithBadTarget=deviceIsIOS&&/OS [6-7]_\d/.test(navigator.userAgent),deviceIsBlackBerry10=navigator.userAgent.indexOf("BB10")>0;FastClick.prototype.needsClick=function(target){switch(target.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(target.disabled)return!0;break;case"input":if(deviceIsIOS&&"file"===target.type||target.disabled)return!0;break;case"label":case"iframe":case"video":return!0}return/\bneedsclick\b/.test(target.className)},FastClick.prototype.needsFocus=function(target){switch(target.nodeName.toLowerCase()){case"textarea":return!0;case"select":return!deviceIsAndroid;case"input":switch(target.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return!1}return!target.disabled&&!target.readOnly;default:return/\bneedsfocus\b/.test(target.className)}},FastClick.prototype.sendClick=function(targetElement,event){var clickEvent,touch;document.activeElement&&document.activeElement!==targetElement&&document.activeElement.blur(),touch=event.changedTouches[0],clickEvent=document.createEvent("MouseEvents"),clickEvent.initMouseEvent(this.determineEventType(targetElement),!0,!0,window,1,touch.screenX,touch.screenY,touch.clientX,touch.clientY,!1,!1,!1,!1,0,null),clickEvent.forwardedTouchEvent=!0,targetElement.dispatchEvent(clickEvent)},FastClick.prototype.determineEventType=function(targetElement){return deviceIsAndroid&&"select"===targetElement.tagName.toLowerCase()?"mousedown":"click"},FastClick.prototype.focus=function(targetElement){var length;deviceIsIOS&&targetElement.setSelectionRange&&0!==targetElement.type.indexOf("date")&&"time"!==targetElement.type&&"month"!==targetElement.type?(length=targetElement.value.length,targetElement.setSelectionRange(length,length)):targetElement.focus()},FastClick.prototype.updateScrollParent=function(targetElement){var scrollParent,parentElement;if(scrollParent=targetElement.fastClickScrollParent,!scrollParent||!scrollParent.contains(targetElement)){parentElement=targetElement;do{if(parentElement.scrollHeight>parentElement.offsetHeight){scrollParent=parentElement,targetElement.fastClickScrollParent=parentElement;break}parentElement=parentElement.parentElement}while(parentElement)}scrollParent&&(scrollParent.fastClickLastScrollTop=scrollParent.scrollTop)},FastClick.prototype.getTargetElementFromEventTarget=function(eventTarget){return eventTarget.nodeType===Node.TEXT_NODE?eventTarget.parentNode:eventTarget},FastClick.prototype.onTouchStart=function(event){var targetElement,touch,selection;if(event.targetTouches.length>1)return!0;if(targetElement=this.getTargetElementFromEventTarget(event.target),touch=event.targetTouches[0],deviceIsIOS){if(selection=window.getSelection(),selection.rangeCount&&!selection.isCollapsed)return!0;if(!deviceIsIOS4){if(touch.identifier&&touch.identifier===this.lastTouchIdentifier)return event.preventDefault(),!1;this.lastTouchIdentifier=touch.identifier,this.updateScrollParent(targetElement)}}return this.trackingClick=!0,this.trackingClickStart=event.timeStamp,this.targetElement=targetElement,this.touchStartX=touch.pageX,this.touchStartY=touch.pageY,event.timeStamp-this.lastClickTime<this.tapDelay&&event.timeStamp-this.lastClickTime>-1&&event.preventDefault(),!0},FastClick.prototype.touchHasMoved=function(event){var touch=event.changedTouches[0],boundary=this.touchBoundary;return Math.abs(touch.pageX-this.touchStartX)>boundary||Math.abs(touch.pageY-this.touchStartY)>boundary?!0:!1},FastClick.prototype.onTouchMove=function(event){return this.trackingClick?((this.targetElement!==this.getTargetElementFromEventTarget(event.target)||this.touchHasMoved(event))&&(this.trackingClick=!1,this.targetElement=null),!0):!0},FastClick.prototype.findControl=function(labelElement){return void 0!==labelElement.control?labelElement.control:labelElement.htmlFor?document.getElementById(labelElement.htmlFor):labelElement.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")},FastClick.prototype.onTouchEnd=function(event){var forElement,trackingClickStart,targetTagName,scrollParent,touch,targetElement=this.targetElement;if(!this.trackingClick)return!0;if(event.timeStamp-this.lastClickTime<this.tapDelay&&event.timeStamp-this.lastClickTime>-1)return this.cancelNextClick=!0,!0;if(event.timeStamp-this.trackingClickStart>this.tapTimeout)return!0;if(this.cancelNextClick=!1,this.lastClickTime=event.timeStamp,trackingClickStart=this.trackingClickStart,this.trackingClick=!1,this.trackingClickStart=0,deviceIsIOSWithBadTarget&&(touch=event.changedTouches[0],targetElement=document.elementFromPoint(touch.pageX-window.pageXOffset,touch.pageY-window.pageYOffset)||targetElement,targetElement.fastClickScrollParent=this.targetElement.fastClickScrollParent),targetTagName=targetElement.tagName.toLowerCase(),"label"===targetTagName){if(forElement=this.findControl(targetElement)){if(this.focus(targetElement),deviceIsAndroid)return!1;targetElement=forElement}}else if(this.needsFocus(targetElement))return event.timeStamp-trackingClickStart>100||deviceIsIOS&&window.top!==window&&"input"===targetTagName?(this.targetElement=null,!1):(this.focus(targetElement),this.sendClick(targetElement,event),deviceIsIOS&&"select"===targetTagName||(this.targetElement=null,event.preventDefault()),!1);return deviceIsIOS&&!deviceIsIOS4&&(scrollParent=targetElement.fastClickScrollParent,scrollParent&&scrollParent.fastClickLastScrollTop!==scrollParent.scrollTop)?!0:(this.needsClick(targetElement)||(event.preventDefault(),this.sendClick(targetElement,event)),!1)},FastClick.prototype.onTouchCancel=function(){this.trackingClick=!1,this.targetElement=null},FastClick.prototype.onMouse=function(event){return this.targetElement?event.forwardedTouchEvent?!0:event.cancelable&&(!this.needsClick(this.targetElement)||this.cancelNextClick)?(event.stopImmediatePropagation?event.stopImmediatePropagation():event.propagationStopped=!0,event.stopPropagation(),event.preventDefault(),!1):!0:!0},FastClick.prototype.onClick=function(event){var permitted;return this.trackingClick?(this.targetElement=null,this.trackingClick=!1,!0):"submit"===event.target.type&&0===event.detail?!0:(permitted=this.onMouse(event),permitted||(this.targetElement=null),permitted)},FastClick.prototype.destroy=function(){var layer=this.layer;deviceIsAndroid&&(layer.removeEventListener("mouseover",this.onMouse,!0),layer.removeEventListener("mousedown",this.onMouse,!0),layer.removeEventListener("mouseup",this.onMouse,!0)),layer.removeEventListener("click",this.onClick,!0),layer.removeEventListener("touchstart",this.onTouchStart,!1),layer.removeEventListener("touchmove",this.onTouchMove,!1),layer.removeEventListener("touchend",this.onTouchEnd,!1),layer.removeEventListener("touchcancel",this.onTouchCancel,!1)},FastClick.notNeeded=function(layer){var metaViewport,chromeVersion,blackberryVersion,firefoxVersion;if("undefined"==typeof window.ontouchstart)return!0;if(chromeVersion=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]){if(!deviceIsAndroid)return!0;if(metaViewport=document.querySelector("meta[name=viewport]")){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(chromeVersion>31&&document.documentElement.scrollWidth<=window.outerWidth)return!0}}if(deviceIsBlackBerry10&&(blackberryVersion=navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/),blackberryVersion[1]>=10&&blackberryVersion[2]>=3&&(metaViewport=document.querySelector("meta[name=viewport]")))){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(document.documentElement.scrollWidth<=window.outerWidth)return!0}return"none"===layer.style.msTouchAction||"manipulation"===layer.style.touchAction?!0:(firefoxVersion=+(/Firefox\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1],firefoxVersion>=27&&(metaViewport=document.querySelector("meta[name=viewport]"),metaViewport&&(-1!==metaViewport.content.indexOf("user-scalable=no")||document.documentElement.scrollWidth<=window.outerWidth))?!0:"none"===layer.style.touchAction||"manipulation"===layer.style.touchAction?!0:!1)},FastClick.attach=function(layer,options){return new FastClick(layer,options)},"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return FastClick}):"undefined"!=typeof module&&module.exports?(module.exports=FastClick.attach,module.exports.FastClick=FastClick):window.FastClick=FastClick}(),function(window,undefined){"use strict";function setup(){Hammer.READY||(Event.determineEventTypes(),Utils.each(Hammer.gestures,function(gesture){Detection.register(gesture)}),Event.onTouch(Hammer.DOCUMENT,EVENT_MOVE,Detection.detect),Event.onTouch(Hammer.DOCUMENT,EVENT_END,Detection.detect),Hammer.READY=!0)}var Hammer=function Hammer(element,options){return new Hammer.Instance(element,options||{})};Hammer.VERSION="1.1.3",Hammer.defaults={behavior:{userSelect:"none",touchAction:"pan-y",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}},Hammer.DOCUMENT=document,Hammer.HAS_POINTEREVENTS=navigator.pointerEnabled||navigator.msPointerEnabled,Hammer.HAS_TOUCHEVENTS="ontouchstart"in window,Hammer.IS_MOBILE=/mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent),Hammer.NO_MOUSEEVENTS=Hammer.HAS_TOUCHEVENTS&&Hammer.IS_MOBILE||Hammer.HAS_POINTEREVENTS,Hammer.CALCULATE_INTERVAL=25;var EVENT_TYPES={},DIRECTION_DOWN=Hammer.DIRECTION_DOWN="down",DIRECTION_LEFT=Hammer.DIRECTION_LEFT="left",DIRECTION_UP=Hammer.DIRECTION_UP="up",DIRECTION_RIGHT=Hammer.DIRECTION_RIGHT="right",POINTER_MOUSE=Hammer.POINTER_MOUSE="mouse",POINTER_TOUCH=Hammer.POINTER_TOUCH="touch",POINTER_PEN=Hammer.POINTER_PEN="pen",EVENT_START=Hammer.EVENT_START="start",EVENT_MOVE=Hammer.EVENT_MOVE="move",EVENT_END=Hammer.EVENT_END="end",EVENT_RELEASE=Hammer.EVENT_RELEASE="release",EVENT_TOUCH=Hammer.EVENT_TOUCH="touch";Hammer.READY=!1,Hammer.plugins=Hammer.plugins||{},Hammer.gestures=Hammer.gestures||{};var Utils=Hammer.utils={extend:function(dest,src,merge){for(var key in src)!src.hasOwnProperty(key)||dest[key]!==undefined&&merge||(dest[key]=src[key]);return dest},on:function(element,type,handler){element.addEventListener(type,handler,!1)},off:function(element,type,handler){element.removeEventListener(type,handler,!1)},each:function(obj,iterator,context){var i,len;if("forEach"in obj)obj.forEach(iterator,context);else if(obj.length!==undefined){for(i=0,len=obj.length;len>i;i++)if(iterator.call(context,obj[i],i,obj)===!1)return}else for(i in obj)if(obj.hasOwnProperty(i)&&iterator.call(context,obj[i],i,obj)===!1)return},inStr:function(src,find){return src.indexOf(find)>-1},inArray:function(src,find){if(src.indexOf){var index=src.indexOf(find);return-1===index?!1:index}for(var i=0,len=src.length;len>i;i++)if(src[i]===find)return i;return!1},toArray:function(obj){return Array.prototype.slice.call(obj,0)},hasParent:function(node,parent){for(;node;){if(node==parent)return!0;node=node.parentNode}return!1},getCenter:function(touches){var pageX=[],pageY=[],clientX=[],clientY=[],min=Math.min,max=Math.max;return 1===touches.length?{pageX:touches[0].pageX,pageY:touches[0].pageY,clientX:touches[0].clientX,clientY:touches[0].clientY}:(Utils.each(touches,function(touch){pageX.push(touch.pageX),pageY.push(touch.pageY),clientX.push(touch.clientX),clientY.push(touch.clientY)}),{pageX:(min.apply(Math,pageX)+max.apply(Math,pageX))/2,pageY:(min.apply(Math,pageY)+max.apply(Math,pageY))/2,clientX:(min.apply(Math,clientX)+max.apply(Math,clientX))/2,clientY:(min.apply(Math,clientY)+max.apply(Math,clientY))/2})},getVelocity:function(deltaTime,deltaX,deltaY){return{x:Math.abs(deltaX/deltaTime)||0,y:Math.abs(deltaY/deltaTime)||0}},getAngle:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return 180*Math.atan2(y,x)/Math.PI},getDirection:function(touch1,touch2){var x=Math.abs(touch1.clientX-touch2.clientX),y=Math.abs(touch1.clientY-touch2.clientY);return x>=y?touch1.clientX-touch2.clientX>0?DIRECTION_LEFT:DIRECTION_RIGHT:touch1.clientY-touch2.clientY>0?DIRECTION_UP:DIRECTION_DOWN},getDistance:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return Math.sqrt(x*x+y*y)},getScale:function(start,end){return start.length>=2&&end.length>=2?this.getDistance(end[0],end[1])/this.getDistance(start[0],start[1]):1},getRotation:function(start,end){return start.length>=2&&end.length>=2?this.getAngle(end[1],end[0])-this.getAngle(start[1],start[0]):0},isVertical:function(direction){return direction==DIRECTION_UP||direction==DIRECTION_DOWN},setPrefixedCss:function(element,prop,value,toggle){var prefixes=["","Webkit","Moz","O","ms"];prop=Utils.toCamelCase(prop);for(var i=0;i<prefixes.length;i++){var p=prop;if(prefixes[i]&&(p=prefixes[i]+p.slice(0,1).toUpperCase()+p.slice(1)),p in element.style){element.style[p]=(null==toggle||toggle)&&value||"";break}}},toggleBehavior:function(element,props,toggle){if(props&&element&&element.style){Utils.each(props,function(value,prop){Utils.setPrefixedCss(element,prop,value,toggle)});var falseFn=toggle&&function(){return!1};"none"==props.userSelect&&(element.onselectstart=falseFn),"none"==props.userDrag&&(element.ondragstart=falseFn)}},toCamelCase:function(str){return str.replace(/[_-]([a-z])/g,function(s){return s[1].toUpperCase()})}},Event=Hammer.event={preventMouseEvents:!1,started:!1,shouldDetect:!1,on:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.on(element,type,handler),hook&&hook(type)})},off:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.off(element,type,handler),hook&&hook(type)})},onTouch:function(element,eventType,handler){var self=this,onTouchHandler=function(ev){var triggerType,srcType=ev.type.toLowerCase(),isPointer=Hammer.HAS_POINTEREVENTS,isMouse=Utils.inStr(srcType,"mouse");isMouse&&self.preventMouseEvents||(isMouse&&eventType==EVENT_START&&0===ev.button?(self.preventMouseEvents=!1,self.shouldDetect=!0):isPointer&&eventType==EVENT_START?self.shouldDetect=1===ev.buttons||PointerEvent.matchType(POINTER_TOUCH,ev):isMouse||eventType!=EVENT_START||(self.preventMouseEvents=!0,self.shouldDetect=!0),isPointer&&eventType!=EVENT_END&&PointerEvent.updatePointer(eventType,ev),self.shouldDetect&&(triggerType=self.doDetect.call(self,ev,eventType,element,handler)),triggerType==EVENT_END&&(self.preventMouseEvents=!1,self.shouldDetect=!1,PointerEvent.reset()),isPointer&&eventType==EVENT_END&&PointerEvent.updatePointer(eventType,ev))};return this.on(element,EVENT_TYPES[eventType],onTouchHandler),onTouchHandler},doDetect:function(ev,eventType,element,handler){var touchList=this.getTouchList(ev,eventType),touchListLength=touchList.length,triggerType=eventType,triggerChange=touchList.trigger,changedLength=touchListLength;eventType==EVENT_START?triggerChange=EVENT_TOUCH:eventType==EVENT_END&&(triggerChange=EVENT_RELEASE,changedLength=touchList.length-(ev.changedTouches?ev.changedTouches.length:1)),changedLength>0&&this.started&&(triggerType=EVENT_MOVE),this.started=!0;var evData=this.collectEventData(element,triggerType,touchList,ev);return eventType!=EVENT_END&&handler.call(Detection,evData),triggerChange&&(evData.changedLength=changedLength,evData.eventType=triggerChange,handler.call(Detection,evData),evData.eventType=triggerType,delete evData.changedLength),triggerType==EVENT_END&&(handler.call(Detection,evData),this.started=!1),triggerType},determineEventTypes:function(){var types;return types=Hammer.HAS_POINTEREVENTS?window.PointerEvent?["pointerdown","pointermove","pointerup pointercancel lostpointercapture"]:["MSPointerDown","MSPointerMove","MSPointerUp MSPointerCancel MSLostPointerCapture"]:Hammer.NO_MOUSEEVENTS?["touchstart","touchmove","touchend touchcancel"]:["touchstart mousedown","touchmove mousemove","touchend touchcancel mouseup"],EVENT_TYPES[EVENT_START]=types[0],EVENT_TYPES[EVENT_MOVE]=types[1],EVENT_TYPES[EVENT_END]=types[2],EVENT_TYPES},getTouchList:function(ev,eventType){if(Hammer.HAS_POINTEREVENTS)return PointerEvent.getTouchList();if(ev.touches){if(eventType==EVENT_MOVE)return ev.touches;var identifiers=[],concat=[].concat(Utils.toArray(ev.touches),Utils.toArray(ev.changedTouches)),touchList=[];return Utils.each(concat,function(touch){Utils.inArray(identifiers,touch.identifier)===!1&&touchList.push(touch),identifiers.push(touch.identifier)}),touchList}return ev.identifier=1,[ev]},collectEventData:function(element,eventType,touches,ev){var pointerType=POINTER_TOUCH;return Utils.inStr(ev.type,"mouse")||PointerEvent.matchType(POINTER_MOUSE,ev)?pointerType=POINTER_MOUSE:PointerEvent.matchType(POINTER_PEN,ev)&&(pointerType=POINTER_PEN),{center:Utils.getCenter(touches),timeStamp:Date.now(),target:ev.target,touches:touches,eventType:eventType,pointerType:pointerType,srcEvent:ev,preventDefault:function(){var srcEvent=this.srcEvent;srcEvent.preventManipulation&&srcEvent.preventManipulation(),srcEvent.preventDefault&&srcEvent.preventDefault()},stopPropagation:function(){this.srcEvent.stopPropagation()},stopDetect:function(){return Detection.stopDetect()}}}},PointerEvent=Hammer.PointerEvent={pointers:{},getTouchList:function(){var touchlist=[];return Utils.each(this.pointers,function(pointer){touchlist.push(pointer)}),touchlist},updatePointer:function(eventType,pointerEvent){eventType==EVENT_END||eventType!=EVENT_END&&1!==pointerEvent.buttons?delete this.pointers[pointerEvent.pointerId]:(pointerEvent.identifier=pointerEvent.pointerId,this.pointers[pointerEvent.pointerId]=pointerEvent)},matchType:function(pointerType,ev){if(!ev.pointerType)return!1;var pt=ev.pointerType,types={};return types[POINTER_MOUSE]=pt===(ev.MSPOINTER_TYPE_MOUSE||POINTER_MOUSE),types[POINTER_TOUCH]=pt===(ev.MSPOINTER_TYPE_TOUCH||POINTER_TOUCH),types[POINTER_PEN]=pt===(ev.MSPOINTER_TYPE_PEN||POINTER_PEN),types[pointerType]},reset:function(){this.pointers={}}},Detection=Hammer.detection={gestures:[],current:null,previous:null,stopped:!1,startDetect:function(inst,eventData){this.current||(this.stopped=!1,this.current={inst:inst,startEvent:Utils.extend({},eventData),lastEvent:!1,lastCalcEvent:!1,futureCalcEvent:!1,lastCalcData:{},name:""},this.detect(eventData))},detect:function(eventData){if(this.current&&!this.stopped){eventData=this.extendEventData(eventData);var inst=this.current.inst,instOptions=inst.options;return Utils.each(this.gestures,function(gesture){!this.stopped&&inst.enabled&&instOptions[gesture.name]&&gesture.handler.call(gesture,eventData,inst)},this),this.current&&(this.current.lastEvent=eventData),eventData.eventType==EVENT_END&&this.stopDetect(),eventData}},stopDetect:function(){this.previous=Utils.extend({},this.current),this.current=null,this.stopped=!0},getCalculatedData:function(ev,center,deltaTime,deltaX,deltaY){var cur=this.current,recalc=!1,calcEv=cur.lastCalcEvent,calcData=cur.lastCalcData;calcEv&&ev.timeStamp-calcEv.timeStamp>Hammer.CALCULATE_INTERVAL&&(center=calcEv.center,deltaTime=ev.timeStamp-calcEv.timeStamp,deltaX=ev.center.clientX-calcEv.center.clientX,deltaY=ev.center.clientY-calcEv.center.clientY,recalc=!0),(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(cur.futureCalcEvent=ev),(!cur.lastCalcEvent||recalc)&&(calcData.velocity=Utils.getVelocity(deltaTime,deltaX,deltaY),calcData.angle=Utils.getAngle(center,ev.center),calcData.direction=Utils.getDirection(center,ev.center),cur.lastCalcEvent=cur.futureCalcEvent||ev,cur.futureCalcEvent=ev),ev.velocityX=calcData.velocity.x,ev.velocityY=calcData.velocity.y,ev.interimAngle=calcData.angle,ev.interimDirection=calcData.direction},extendEventData:function(ev){var cur=this.current,startEv=cur.startEvent,lastEv=cur.lastEvent||startEv;(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(startEv.touches=[],Utils.each(ev.touches,function(touch){startEv.touches.push({clientX:touch.clientX,clientY:touch.clientY})}));var deltaTime=ev.timeStamp-startEv.timeStamp,deltaX=ev.center.clientX-startEv.center.clientX,deltaY=ev.center.clientY-startEv.center.clientY;return this.getCalculatedData(ev,lastEv.center,deltaTime,deltaX,deltaY),Utils.extend(ev,{startEvent:startEv,deltaTime:deltaTime,deltaX:deltaX,deltaY:deltaY,distance:Utils.getDistance(startEv.center,ev.center),angle:Utils.getAngle(startEv.center,ev.center),direction:Utils.getDirection(startEv.center,ev.center),scale:Utils.getScale(startEv.touches,ev.touches),rotation:Utils.getRotation(startEv.touches,ev.touches)}),ev},register:function(gesture){var options=gesture.defaults||{};return options[gesture.name]===undefined&&(options[gesture.name]=!0),Utils.extend(Hammer.defaults,options,!0),gesture.index=gesture.index||1e3,this.gestures.push(gesture),this.gestures.sort(function(a,b){return a.index<b.index?-1:a.index>b.index?1:0}),this.gestures}};Hammer.Instance=function(element,options){var self=this;setup(),this.element=element,this.enabled=!0,Utils.each(options,function(value,name){delete options[name],options[Utils.toCamelCase(name)]=value}),this.options=Utils.extend(Utils.extend({},Hammer.defaults),options||{}),this.options.behavior&&Utils.toggleBehavior(this.element,this.options.behavior,!0),this.eventStartHandler=Event.onTouch(element,EVENT_START,function(ev){self.enabled&&ev.eventType==EVENT_START?Detection.startDetect(self,ev):ev.eventType==EVENT_TOUCH&&Detection.detect(ev)}),this.eventHandlers=[]},Hammer.Instance.prototype={on:function(gestures,handler){var self=this;return Event.on(self.element,gestures,handler,function(type){self.eventHandlers.push({gesture:type,handler:handler})}),self},off:function(gestures,handler){var self=this;return Event.off(self.element,gestures,handler,function(type){var index=Utils.inArray({gesture:type,handler:handler});index!==!1&&self.eventHandlers.splice(index,1)}),self},trigger:function(gesture,eventData){eventData||(eventData={});var event=Hammer.DOCUMENT.createEvent("Event");event.initEvent(gesture,!0,!0),event.gesture=eventData;var element=this.element;return Utils.hasParent(eventData.target,element)&&(element=eventData.target),element.dispatchEvent(event),this},enable:function(state){return this.enabled=state,this},dispose:function(){var i,eh;for(Utils.toggleBehavior(this.element,this.options.behavior,!1),i=-1;eh=this.eventHandlers[++i];)Utils.off(this.element,eh.gesture,eh.handler);return this.eventHandlers=[],Event.off(this.element,EVENT_TYPES[EVENT_START],this.eventStartHandler),null}},function(name){function dragGesture(ev,inst){var cur=Detection.current;if(!(inst.options.dragMaxTouches>0&&ev.touches.length>inst.options.dragMaxTouches))switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.distance<inst.options.dragMinDistance&&cur.name!=name)return;var startCenter=cur.startEvent.center;if(cur.name!=name&&(cur.name=name,inst.options.dragDistanceCorrection&&ev.distance>0)){var factor=Math.abs(inst.options.dragMinDistance/ev.distance);startCenter.pageX+=ev.deltaX*factor,startCenter.pageY+=ev.deltaY*factor,startCenter.clientX+=ev.deltaX*factor,startCenter.clientY+=ev.deltaY*factor,ev=Detection.extendEventData(ev)}(cur.lastEvent.dragLockToAxis||inst.options.dragLockToAxis&&inst.options.dragLockMinDistance<=ev.distance)&&(ev.dragLockToAxis=!0);var lastDirection=cur.lastEvent.direction;ev.dragLockToAxis&&lastDirection!==ev.direction&&(Utils.isVertical(lastDirection)?ev.direction=ev.deltaY<0?DIRECTION_UP:DIRECTION_DOWN:ev.direction=ev.deltaX<0?DIRECTION_LEFT:DIRECTION_RIGHT),triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),inst.trigger(name+ev.direction,ev);var isVertical=Utils.isVertical(ev.direction);(inst.options.dragBlockVertical&&isVertical||inst.options.dragBlockHorizontal&&!isVertical)&&ev.preventDefault();break;case EVENT_RELEASE:triggered&&ev.changedLength<=inst.options.dragMaxTouches&&(inst.trigger(name+"end",ev),triggered=!1);break;case EVENT_END:triggered=!1}}var triggered=!1;Hammer.gestures.Drag={name:name,index:50,handler:dragGesture,defaults:{dragMinDistance:10,dragDistanceCorrection:!0,dragMaxTouches:1,dragBlockHorizontal:!1,dragBlockVertical:!1,dragLockToAxis:!1,dragLockMinDistance:25}}}("drag"),Hammer.gestures.Gesture={name:"gesture",index:1337,handler:function(ev,inst){inst.trigger(this.name,ev)}},function(name){function holdGesture(ev,inst){var options=inst.options,current=Detection.current;switch(ev.eventType){case EVENT_START:clearTimeout(timer),current.name=name,timer=setTimeout(function(){current&&current.name==name&&inst.trigger(name,ev)},options.holdTimeout);break;case EVENT_MOVE:ev.distance>options.holdThreshold&&clearTimeout(timer);break;case EVENT_RELEASE:clearTimeout(timer)}}var timer;Hammer.gestures.Hold={name:name,index:10,defaults:{holdTimeout:500,holdThreshold:2},handler:holdGesture}}("hold"),Hammer.gestures.Release={name:"release",index:1/0,handler:function(ev,inst){ev.eventType==EVENT_RELEASE&&inst.trigger(this.name,ev)}},Hammer.gestures.Swipe={name:"swipe",index:40,defaults:{swipeMinTouches:1,swipeMaxTouches:1,swipeVelocityX:.6,swipeVelocityY:.6},handler:function(ev,inst){if(ev.eventType==EVENT_RELEASE){ var touches=ev.touches.length,options=inst.options;if(touches<options.swipeMinTouches||touches>options.swipeMaxTouches)return;(ev.velocityX>options.swipeVelocityX||ev.velocityY>options.swipeVelocityY)&&(inst.trigger(this.name,ev),inst.trigger(this.name+ev.direction,ev))}}},function(name){function tapGesture(ev,inst){var sincePrev,didDoubleTap,options=inst.options,current=Detection.current,prev=Detection.previous;switch(ev.eventType){case EVENT_START:hasMoved=!1;break;case EVENT_MOVE:hasMoved=hasMoved||ev.distance>options.tapMaxDistance;break;case EVENT_END:!Utils.inStr(ev.srcEvent.type,"cancel")&&ev.deltaTime<options.tapMaxTime&&!hasMoved&&(sincePrev=prev&&prev.lastEvent&&ev.timeStamp-prev.lastEvent.timeStamp,didDoubleTap=!1,prev&&prev.name==name&&sincePrev&&sincePrev<options.doubleTapInterval&&ev.distance<options.doubleTapDistance&&(inst.trigger("doubletap",ev),didDoubleTap=!0),(!didDoubleTap||options.tapAlways)&&(current.name=name,inst.trigger(current.name,ev)))}}var hasMoved=!1;Hammer.gestures.Tap={name:name,index:100,handler:tapGesture,defaults:{tapMaxTime:250,tapMaxDistance:10,tapAlways:!0,doubleTapDistance:20,doubleTapInterval:300}}}("tap"),Hammer.gestures.Touch={name:"touch",index:-(1/0),defaults:{preventDefault:!1,preventMouse:!1},handler:function(ev,inst){return inst.options.preventMouse&&ev.pointerType==POINTER_MOUSE?void ev.stopDetect():(inst.options.preventDefault&&ev.preventDefault(),void(ev.eventType==EVENT_TOUCH&&inst.trigger("touch",ev)))}},function(name){function transformGesture(ev,inst){switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.touches.length<2)return;var scaleThreshold=Math.abs(1-ev.scale),rotationThreshold=Math.abs(ev.rotation);if(scaleThreshold<inst.options.transformMinScale&&rotationThreshold<inst.options.transformMinRotation)return;Detection.current.name=name,triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),rotationThreshold>inst.options.transformMinRotation&&inst.trigger("rotate",ev),scaleThreshold>inst.options.transformMinScale&&(inst.trigger("pinch",ev),inst.trigger("pinch"+(ev.scale<1?"in":"out"),ev));break;case EVENT_RELEASE:triggered&&ev.changedLength<2&&(inst.trigger(name+"end",ev),triggered=!1)}}var triggered=!1;Hammer.gestures.Transform={name:name,index:45,defaults:{transformMinScale:.01,transformMinRotation:1},handler:transformGesture}}("transform"),"function"==typeof define&&define.amd?define(function(){return Hammer}):"undefined"!=typeof module&&module.exports?module.exports=Hammer:window.Hammer=Hammer}(window);var IScroll=function(window,document,Math){function IScroll(el,options){this.wrapper="string"==typeof el?document.querySelector(el):el,this.scroller=this.wrapper.children[0],this.scrollerStyle=this.scroller.style,this.options={startX:0,startY:0,scrollY:!0,directionLockThreshold:5,momentum:!0,bounce:!0,bounceTime:600,bounceEasing:"",preventDefault:!0,preventDefaultException:{tagName:/^(INPUT|TEXTAREA|BUTTON|SELECT)$/},HWCompositing:!0,useTransition:!0,useTransform:!0};for(var i in options)this.options[i]=options[i];this.translateZ=this.options.HWCompositing&&utils.hasPerspective?" translateZ(0)":"",this.options.useTransition=utils.hasTransition&&this.options.useTransition,this.options.useTransform=utils.hasTransform&&this.options.useTransform,this.options.eventPassthrough=this.options.eventPassthrough===!0?"vertical":this.options.eventPassthrough,this.options.preventDefault=!this.options.eventPassthrough&&this.options.preventDefault,this.options.scrollY="vertical"==this.options.eventPassthrough?!1:this.options.scrollY,this.options.scrollX="horizontal"==this.options.eventPassthrough?!1:this.options.scrollX,this.options.freeScroll=this.options.freeScroll&&!this.options.eventPassthrough,this.options.directionLockThreshold=this.options.eventPassthrough?0:this.options.directionLockThreshold,this.options.bounceEasing="string"==typeof this.options.bounceEasing?utils.ease[this.options.bounceEasing]||utils.ease.circular:this.options.bounceEasing,this.options.resizePolling=void 0===this.options.resizePolling?60:this.options.resizePolling,this.options.tap===!0&&(this.options.tap="tap"),this.x=0,this.y=0,this.directionX=0,this.directionY=0,this._events={},this._init(),this.refresh(),this.scrollTo(this.options.startX,this.options.startY),this.enable()}var rAF=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){window.setTimeout(callback,1e3/60)},utils=function(){function _prefixStyle(style){return _vendor===!1?!1:""===_vendor?style:_vendor+style.charAt(0).toUpperCase()+style.substr(1)}var me={},_elementStyle=document.createElement("div").style,_vendor=function(){for(var transform,vendors=["t","webkitT","MozT","msT","OT"],i=0,l=vendors.length;l>i;i++)if(transform=vendors[i]+"ransform",transform in _elementStyle)return vendors[i].substr(0,vendors[i].length-1);return!1}();me.getTime=Date.now||function(){return(new Date).getTime()},me.extend=function(target,obj){for(var i in obj)target[i]=obj[i]},me.addEvent=function(el,type,fn,capture){el.addEventListener(type,fn,!!capture)},me.removeEvent=function(el,type,fn,capture){el.removeEventListener(type,fn,!!capture)},me.momentum=function(current,start,time,lowerMargin,wrapperSize){var destination,duration,distance=current-start,speed=Math.abs(distance)/time,deceleration=6e-4;return destination=current+speed*speed/(2*deceleration)*(0>distance?-1:1),duration=speed/deceleration,lowerMargin>destination?(destination=wrapperSize?lowerMargin-wrapperSize/2.5*(speed/8):lowerMargin,distance=Math.abs(destination-current),duration=distance/speed):destination>0&&(destination=wrapperSize?wrapperSize/2.5*(speed/8):0,distance=Math.abs(current)+destination,duration=distance/speed),{destination:Math.round(destination),duration:duration}};var _transform=_prefixStyle("transform");return me.extend(me,{hasTransform:_transform!==!1,hasPerspective:_prefixStyle("perspective")in _elementStyle,hasTouch:"ontouchstart"in window,hasPointer:navigator.msPointerEnabled,hasTransition:_prefixStyle("transition")in _elementStyle}),me.isAndroidBrowser=/Android/.test(window.navigator.appVersion)&&/Version\/\d/.test(window.navigator.appVersion),me.extend(me.style={},{transform:_transform,transitionTimingFunction:_prefixStyle("transitionTimingFunction"),transitionDuration:_prefixStyle("transitionDuration"),transformOrigin:_prefixStyle("transformOrigin")}),me.hasClass=function(e,c){var re=new RegExp("(^|\\s)"+c+"(\\s|$)");return re.test(e.className)},me.addClass=function(e,c){if(!me.hasClass(e,c)){var newclass=e.className.split(" ");newclass.push(c),e.className=newclass.join(" ")}},me.removeClass=function(e,c){if(me.hasClass(e,c)){var re=new RegExp("(^|\\s)"+c+"(\\s|$)","g");e.className=e.className.replace(re," ")}},me.offset=function(el){for(var left=-el.offsetLeft,top=-el.offsetTop;el=el.offsetParent;)left-=el.offsetLeft,top-=el.offsetTop;return{left:left,top:top}},me.preventDefaultException=function(el,exceptions){for(var i in exceptions)if(exceptions[i].test(el[i]))return!0;return!1},me.extend(me.eventType={},{touchstart:1,touchmove:1,touchend:1,mousedown:2,mousemove:2,mouseup:2,MSPointerDown:3,MSPointerMove:3,MSPointerUp:3}),me.extend(me.ease={},{quadratic:{style:"cubic-bezier(0.25, 0.46, 0.45, 0.94)",fn:function(k){return k*(2-k)}},circular:{style:"cubic-bezier(0.1, 0.57, 0.1, 1)",fn:function(k){return Math.sqrt(1- --k*k)}},back:{style:"cubic-bezier(0.175, 0.885, 0.32, 1.275)",fn:function(k){var b=4;return(k-=1)*k*((b+1)*k+b)+1}},bounce:{style:"",fn:function(k){return(k/=1)<1/2.75?7.5625*k*k:2/2.75>k?7.5625*(k-=1.5/2.75)*k+.75:2.5/2.75>k?7.5625*(k-=2.25/2.75)*k+.9375:7.5625*(k-=2.625/2.75)*k+.984375}},elastic:{style:"",fn:function(k){var f=.22,e=.4;return 0===k?0:1==k?1:e*Math.pow(2,-10*k)*Math.sin((k-f/4)*(2*Math.PI)/f)+1}}}),me.tap=function(e,eventName){var ev=document.createEvent("Event");ev.initEvent(eventName,!0,!0),ev.pageX=e.pageX,ev.pageY=e.pageY,e.target.dispatchEvent(ev)},me.click=function(e){var ev,target=e.target;"SELECT"!=target.tagName&&"INPUT"!=target.tagName&&"TEXTAREA"!=target.tagName&&(ev=document.createEvent("MouseEvents"),ev.initMouseEvent("click",!0,!0,e.view,1,target.screenX,target.screenY,target.clientX,target.clientY,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,0,null),ev._constructed=!0,target.dispatchEvent(ev))},me}();return IScroll.prototype={version:"5.0.6",_init:function(){this._initEvents()},destroy:function(){this._initEvents(!0),this._execEvent("destroy")},_transitionEnd:function(e){e.target==this.scroller&&(this._transitionTime(0),this.resetPosition(this.options.bounceTime)||this._execEvent("scrollEnd"))},_start:function(e){if((1==utils.eventType[e.type]||0===e.button)&&this.enabled&&(!this.initiated||utils.eventType[e.type]===this.initiated)){!this.options.preventDefault||utils.isAndroidBrowser||utils.preventDefaultException(e.target,this.options.preventDefaultException)||e.preventDefault();var pos,point=e.touches?e.touches[0]:e;this.initiated=utils.eventType[e.type],this.moved=!1,this.distX=0,this.distY=0,this.directionX=0,this.directionY=0,this.directionLocked=0,this._transitionTime(),this.isAnimating=!1,this.startTime=utils.getTime(),this.options.useTransition&&this.isInTransition&&(pos=this.getComputedPosition(),this._translate(Math.round(pos.x),Math.round(pos.y)),this._execEvent("scrollEnd"),this.isInTransition=!1),this.startX=this.x,this.startY=this.y,this.absStartX=this.x,this.absStartY=this.y,this.pointX=point.pageX,this.pointY=point.pageY,this._execEvent("beforeScrollStart")}},_move:function(e){if(this.enabled&&utils.eventType[e.type]===this.initiated){this.options.preventDefault&&e.preventDefault();var newX,newY,absDistX,absDistY,point=e.touches?e.touches[0]:e,deltaX=point.pageX-this.pointX,deltaY=point.pageY-this.pointY,timestamp=utils.getTime();if(this.pointX=point.pageX,this.pointY=point.pageY,this.distX+=deltaX,this.distY+=deltaY,absDistX=Math.abs(this.distX),absDistY=Math.abs(this.distY),!(timestamp-this.endTime>300&&10>absDistX&&10>absDistY)){if(this.directionLocked||this.options.freeScroll||(absDistX>absDistY+this.options.directionLockThreshold?this.directionLocked="h":absDistY>=absDistX+this.options.directionLockThreshold?this.directionLocked="v":this.directionLocked="n"),"h"==this.directionLocked){if("vertical"==this.options.eventPassthrough)e.preventDefault();else if("horizontal"==this.options.eventPassthrough)return void(this.initiated=!1);deltaY=0}else if("v"==this.directionLocked){if("horizontal"==this.options.eventPassthrough)e.preventDefault();else if("vertical"==this.options.eventPassthrough)return void(this.initiated=!1);deltaX=0}deltaX=this.hasHorizontalScroll?deltaX:0,deltaY=this.hasVerticalScroll?deltaY:0,newX=this.x+deltaX,newY=this.y+deltaY,(newX>0||newX<this.maxScrollX)&&(newX=this.options.bounce?this.x+deltaX/3:newX>0?0:this.maxScrollX),(newY>0||newY<this.maxScrollY)&&(newY=this.options.bounce?this.y+deltaY/3:newY>0?0:this.maxScrollY),this.directionX=deltaX>0?-1:0>deltaX?1:0,this.directionY=deltaY>0?-1:0>deltaY?1:0,this.moved||this._execEvent("scrollStart"),this.moved=!0,this._translate(newX,newY),timestamp-this.startTime>300&&(this.startTime=timestamp,this.startX=this.x,this.startY=this.y)}}},_end:function(e){if(this.enabled&&utils.eventType[e.type]===this.initiated){this.options.preventDefault&&!utils.preventDefaultException(e.target,this.options.preventDefaultException)&&e.preventDefault();var momentumX,momentumY,duration=(e.changedTouches?e.changedTouches[0]:e,utils.getTime()-this.startTime),newX=Math.round(this.x),newY=Math.round(this.y),distanceX=Math.abs(newX-this.startX),distanceY=Math.abs(newY-this.startY),time=0,easing="";if(this.scrollTo(newX,newY),this.isInTransition=0,this.initiated=0,this.endTime=utils.getTime(),!this.resetPosition(this.options.bounceTime))return this.moved?this._events.flick&&200>duration&&100>distanceX&&100>distanceY?void this._execEvent("flick"):(this.options.momentum&&300>duration&&(momentumX=this.hasHorizontalScroll?utils.momentum(this.x,this.startX,duration,this.maxScrollX,this.options.bounce?this.wrapperWidth:0):{destination:newX,duration:0},momentumY=this.hasVerticalScroll?utils.momentum(this.y,this.startY,duration,this.maxScrollY,this.options.bounce?this.wrapperHeight:0):{destination:newY,duration:0},newX=momentumX.destination,newY=momentumY.destination,time=Math.max(momentumX.duration,momentumY.duration),this.isInTransition=1),newX!=this.x||newY!=this.y?((newX>0||newX<this.maxScrollX||newY>0||newY<this.maxScrollY)&&(easing=utils.ease.quadratic),void this.scrollTo(newX,newY,time,easing)):void this._execEvent("scrollEnd")):(this.options.tap&&utils.tap(e,this.options.tap),void(this.options.click&&utils.click(e)))}},_resize:function(){var that=this;clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(function(){that.refresh()},this.options.resizePolling)},resetPosition:function(time){var x=this.x,y=this.y;return time=time||0,!this.hasHorizontalScroll||this.x>0?x=0:this.x<this.maxScrollX&&(x=this.maxScrollX),!this.hasVerticalScroll||this.y>0?y=0:this.y<this.maxScrollY&&(y=this.maxScrollY),x==this.x&&y==this.y?!1:(this.scrollTo(x,y,time,this.options.bounceEasing),!0)},disable:function(){this.enabled=!1},enable:function(){this.enabled=!0},refresh:function(){this.wrapper.offsetHeight;this.wrapperWidth=this.wrapper.clientWidth,this.wrapperHeight=this.wrapper.clientHeight,this.scrollerWidth=this.scroller.offsetWidth,this.scrollerHeight=this.scroller.offsetHeight,this.maxScrollX=this.wrapperWidth-this.scrollerWidth,this.maxScrollY=this.wrapperHeight-this.scrollerHeight,this.hasHorizontalScroll=this.options.scrollX&&this.maxScrollX<0,this.hasVerticalScroll=this.options.scrollY&&this.maxScrollY<0,this.hasHorizontalScroll||(this.maxScrollX=0,this.scrollerWidth=this.wrapperWidth),this.hasVerticalScroll||(this.maxScrollY=0,this.scrollerHeight=this.wrapperHeight),this.endTime=0,this.directionX=0,this.directionY=0,this.wrapperOffset=utils.offset(this.wrapper),this._execEvent("refresh"),this.resetPosition()},on:function(type,fn){this._events[type]||(this._events[type]=[]),this._events[type].push(fn)},_execEvent:function(type){if(this._events[type]){var i=0,l=this._events[type].length;if(l)for(;l>i;i++)this._events[type][i].call(this)}},scrollBy:function(x,y,time,easing){x=this.x+x,y=this.y+y,time=time||0,this.scrollTo(x,y,time,easing)},scrollTo:function(x,y,time,easing){easing=easing||utils.ease.circular,!time||this.options.useTransition&&easing.style?(this._transitionTimingFunction(easing.style),this._transitionTime(time),this._translate(x,y)):this._animate(x,y,time,easing.fn)},scrollToElement:function(el,time,offsetX,offsetY,easing){if(el=el.nodeType?el:this.scroller.querySelector(el)){var pos=utils.offset(el);pos.left-=this.wrapperOffset.left,pos.top-=this.wrapperOffset.top,offsetX===!0&&(offsetX=Math.round(el.offsetWidth/2-this.wrapper.offsetWidth/2)),offsetY===!0&&(offsetY=Math.round(el.offsetHeight/2-this.wrapper.offsetHeight/2)),pos.left-=offsetX||0,pos.top-=offsetY||0,pos.left=pos.left>0?0:pos.left<this.maxScrollX?this.maxScrollX:pos.left,pos.top=pos.top>0?0:pos.top<this.maxScrollY?this.maxScrollY:pos.top,time=void 0===time||null===time||"auto"===time?Math.max(Math.abs(this.x-pos.left),Math.abs(this.y-pos.top)):time,this.scrollTo(pos.left,pos.top,time,easing)}},_transitionTime:function(time){time=time||0,this.scrollerStyle[utils.style.transitionDuration]=time+"ms"},_transitionTimingFunction:function(easing){this.scrollerStyle[utils.style.transitionTimingFunction]=easing},_translate:function(x,y){this.options.useTransform?this.scrollerStyle[utils.style.transform]="translate("+x+"px,"+y+"px)"+this.translateZ:(x=Math.round(x),y=Math.round(y),this.scrollerStyle.left=x+"px",this.scrollerStyle.top=y+"px"),this.x=x,this.y=y},_initEvents:function(remove){var eventType=remove?utils.removeEvent:utils.addEvent,target=this.options.bindToWrapper?this.wrapper:window;eventType(window,"orientationchange",this),eventType(window,"resize",this),this.options.click&&eventType(this.wrapper,"click",this,!0),this.options.disableMouse||(eventType(this.wrapper,"mousedown",this),eventType(target,"mousemove",this),eventType(target,"mousecancel",this),eventType(target,"mouseup",this)),utils.hasPointer&&!this.options.disablePointer&&(eventType(this.wrapper,"MSPointerDown",this),eventType(target,"MSPointerMove",this),eventType(target,"MSPointerCancel",this),eventType(target,"MSPointerUp",this)),utils.hasTouch&&!this.options.disableTouch&&(eventType(this.wrapper,"touchstart",this),eventType(target,"touchmove",this),eventType(target,"touchcancel",this),eventType(target,"touchend",this)),eventType(this.scroller,"transitionend",this),eventType(this.scroller,"webkitTransitionEnd",this),eventType(this.scroller,"oTransitionEnd",this),eventType(this.scroller,"MSTransitionEnd",this)},getComputedPosition:function(){var x,y,matrix=window.getComputedStyle(this.scroller,null);return this.options.useTransform?(matrix=matrix[utils.style.transform].split(")")[0].split(", "),x=+(matrix[12]||matrix[4]),y=+(matrix[13]||matrix[5])):(x=+matrix.left.replace(/[^-\d]/g,""),y=+matrix.top.replace(/[^-\d]/g,"")),{x:x,y:y}},_animate:function(destX,destY,duration,easingFn){function step(){var newX,newY,easing,now=utils.getTime();return now>=destTime?(that.isAnimating=!1,that._translate(destX,destY),void(that.resetPosition(that.options.bounceTime)||that._execEvent("scrollEnd"))):(now=(now-startTime)/duration,easing=easingFn(now),newX=(destX-startX)*easing+startX,newY=(destY-startY)*easing+startY,that._translate(newX,newY),void(that.isAnimating&&rAF(step)))}var that=this,startX=this.x,startY=this.y,startTime=utils.getTime(),destTime=startTime+duration;this.isAnimating=!0,step()},handleEvent:function(e){switch(e.type){case"touchstart":case"MSPointerDown":case"mousedown":this._start(e);break;case"touchmove":case"MSPointerMove":case"mousemove":this._move(e);break;case"touchend":case"MSPointerUp":case"mouseup":case"touchcancel":case"MSPointerCancel":case"mousecancel":this._end(e);break;case"orientationchange":case"resize":this._resize();break;case"transitionend":case"webkitTransitionEnd":case"oTransitionEnd":case"MSTransitionEnd":this._transitionEnd(e);break;case"DOMMouseScroll":case"mousewheel":this._wheel(e);break;case"keydown":this._key(e);break;case"click":e._constructed||(e.preventDefault(),e.stopPropagation())}}},IScroll.ease=utils.ease,IScroll}(window,document,Math),MicroEvent=function(){};MicroEvent.prototype={on:function(event,fct){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fct)},once:function(event,fct){var self=this,wrapper=function(){return self.off(event,wrapper),fct.apply(null,arguments)};this.on(event,wrapper)},off:function(event,fct){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fct),1)},emit:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},MicroEvent.mixin=function(destObject){for(var props=["on","once","off","emit"],i=0;i<props.length;i++)"function"==typeof destObject?destObject.prototype[props[i]]=MicroEvent.prototype[props[i]]:destObject[props[i]]=MicroEvent.prototype[props[i]]},"undefined"!=typeof module&&"exports"in module&&(module.exports=MicroEvent),window.Modernizr=function(window,document,undefined){function setCss(str){mStyle.cssText=str}function is(obj,type){return typeof obj===type}function contains(str,substr){return!!~(""+str).indexOf(substr)}function testProps(props,prefixed){for(var i in props){var prop=props[i];if(!contains(prop,"-")&&mStyle[prop]!==undefined)return"pfx"==prefixed?prop:!0}return!1}function testDOMProps(props,obj,elem){for(var i in props){var item=obj[props[i]];if(item!==undefined)return elem===!1?props[i]:is(item,"function")?item.bind(elem||obj):item}return!1}function testPropsAll(prop,prefixed,elem){var ucProp=prop.charAt(0).toUpperCase()+prop.slice(1),props=(prop+" "+cssomPrefixes.join(ucProp+" ")+ucProp).split(" ");return is(prefixed,"string")||is(prefixed,"undefined")?testProps(props,prefixed):(props=(prop+" "+domPrefixes.join(ucProp+" ")+ucProp).split(" "),testDOMProps(props,prefixed,elem))}var inputElem,featureName,hasOwnProp,version="2.6.2",Modernizr={},enableClasses=!0,docElement=document.documentElement,mod="modernizr",modElem=document.createElement(mod),mStyle=modElem.style,prefixes=({}.toString," -webkit- -moz- -o- -ms- ".split(" ")),omPrefixes="Webkit Moz O ms",cssomPrefixes=omPrefixes.split(" "),domPrefixes=omPrefixes.toLowerCase().split(" "),ns={svg:"http://www.w3.org/2000/svg"},tests={},classes=[],slice=classes.slice,injectElementWithStyles=function(rule,callback,nodes,testnames){var style,ret,node,docOverflow,div=document.createElement("div"),body=document.body,fakeBody=body||document.createElement("body");if(parseInt(nodes,10))for(;nodes--;)node=document.createElement("div"),node.id=testnames?testnames[nodes]:mod+(nodes+1),div.appendChild(node);return style=["&#173;",'<style id="s',mod,'">',rule,"</style>"].join(""),div.id=mod,(body?div:fakeBody).innerHTML+=style,fakeBody.appendChild(div),body||(fakeBody.style.background="",fakeBody.style.overflow="hidden",docOverflow=docElement.style.overflow,docElement.style.overflow="hidden",docElement.appendChild(fakeBody)),ret=callback(div,rule),body?div.parentNode.removeChild(div):(fakeBody.parentNode.removeChild(fakeBody),docElement.style.overflow=docOverflow),!!ret},_hasOwnProperty={}.hasOwnProperty;hasOwnProp=is(_hasOwnProperty,"undefined")||is(_hasOwnProperty.call,"undefined")?function(object,property){return property in object&&is(object.constructor.prototype[property],"undefined")}:function(object,property){return _hasOwnProperty.call(object,property)},Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if("function"!=typeof target)throw new TypeError;var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var F=function(){};F.prototype=target.prototype;var self=new F,result=target.apply(self,args.concat(slice.call(arguments)));return Object(result)===result?result:self}return target.apply(that,args.concat(slice.call(arguments)))};return bound}),tests.canvas=function(){var elem=document.createElement("canvas");return!(!elem.getContext||!elem.getContext("2d"))},tests.borderradius=function(){return testPropsAll("borderRadius")},tests.boxshadow=function(){return testPropsAll("boxShadow")},tests.cssanimations=function(){return testPropsAll("animationName")},tests.csstransforms=function(){return!!testPropsAll("transform")},tests.csstransforms3d=function(){var ret=!!testPropsAll("perspective");return ret&&"webkitPerspective"in docElement.style&&injectElementWithStyles("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(node,rule){ret=9===node.offsetLeft&&3===node.offsetHeight}),ret},tests.csstransitions=function(){return testPropsAll("transition")},tests.svg=function(){return!!document.createElementNS&&!!document.createElementNS(ns.svg,"svg").createSVGRect};for(var feature in tests)hasOwnProp(tests,feature)&&(featureName=feature.toLowerCase(),Modernizr[featureName]=tests[feature](),classes.push((Modernizr[featureName]?"":"no-")+featureName));return Modernizr.addTest=function(feature,test){if("object"==typeof feature)for(var key in feature)hasOwnProp(feature,key)&&Modernizr.addTest(key,feature[key]);else{if(feature=feature.toLowerCase(),Modernizr[feature]!==undefined)return Modernizr;test="function"==typeof test?test():test,"undefined"!=typeof enableClasses&&enableClasses&&(docElement.className+=" "+(test?"":"no-")+feature),Modernizr[feature]=test}return Modernizr},setCss(""),modElem=inputElem=null,function(window,document){function addStyleSheet(ownerDocument,cssText){var p=ownerDocument.createElement("p"),parent=ownerDocument.getElementsByTagName("head")[0]||ownerDocument.documentElement;return p.innerHTML="x<style>"+cssText+"</style>",parent.insertBefore(p.lastChild,parent.firstChild)}function getElements(){var elements=html5.elements;return"string"==typeof elements?elements.split(" "):elements}function getExpandoData(ownerDocument){var data=expandoData[ownerDocument[expando]];return data||(data={},expanID++,ownerDocument[expando]=expanID,expandoData[expanID]=data),data}function createElement(nodeName,ownerDocument,data){if(ownerDocument||(ownerDocument=document),supportsUnknownElements)return ownerDocument.createElement(nodeName);data||(data=getExpandoData(ownerDocument));var node;return node=data.cache[nodeName]?data.cache[nodeName].cloneNode():saveClones.test(nodeName)?(data.cache[nodeName]=data.createElem(nodeName)).cloneNode():data.createElem(nodeName),node.canHaveChildren&&!reSkip.test(nodeName)?data.frag.appendChild(node):node}function createDocumentFragment(ownerDocument,data){if(ownerDocument||(ownerDocument=document),supportsUnknownElements)return ownerDocument.createDocumentFragment();data=data||getExpandoData(ownerDocument);for(var clone=data.frag.cloneNode(),i=0,elems=getElements(),l=elems.length;l>i;i++)clone.createElement(elems[i]);return clone}function shivMethods(ownerDocument,data){data.cache||(data.cache={},data.createElem=ownerDocument.createElement,data.createFrag=ownerDocument.createDocumentFragment,data.frag=data.createFrag()),ownerDocument.createElement=function(nodeName){return html5.shivMethods?createElement(nodeName,ownerDocument,data):data.createElem(nodeName)},ownerDocument.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+getElements().join().replace(/\w+/g,function(nodeName){return data.createElem(nodeName),data.frag.createElement(nodeName),'c("'+nodeName+'")'})+");return n}")(html5,data.frag)}function shivDocument(ownerDocument){ownerDocument||(ownerDocument=document);var data=getExpandoData(ownerDocument);return!html5.shivCSS||supportsHtml5Styles||data.hasCSS||(data.hasCSS=!!addStyleSheet(ownerDocument,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),supportsUnknownElements||shivMethods(ownerDocument,data),ownerDocument}var supportsHtml5Styles,supportsUnknownElements,options=window.html5||{},reSkip=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,saveClones=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,expando="_html5shiv",expanID=0,expandoData={};!function(){try{var a=document.createElement("a");a.innerHTML="<xyz></xyz>",supportsHtml5Styles="hidden"in a,supportsUnknownElements=1==a.childNodes.length||function(){document.createElement("a");var frag=document.createDocumentFragment();return"undefined"==typeof frag.cloneNode||"undefined"==typeof frag.createDocumentFragment||"undefined"==typeof frag.createElement}()}catch(e){supportsHtml5Styles=!0,supportsUnknownElements=!0}}();var html5={elements:options.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:options.shivCSS!==!1,supportsUnknownElements:supportsUnknownElements,shivMethods:options.shivMethods!==!1,type:"default",shivDocument:shivDocument,createElement:createElement,createDocumentFragment:createDocumentFragment};window.html5=html5,shivDocument(document)}(this,document),Modernizr._version=version,Modernizr._prefixes=prefixes,Modernizr._domPrefixes=domPrefixes,Modernizr._cssomPrefixes=cssomPrefixes,Modernizr.testProp=function(prop){return testProps([prop])},Modernizr.testAllProps=testPropsAll,Modernizr.testStyles=injectElementWithStyles,docElement.className=docElement.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(enableClasses?" js "+classes.join(" "):""),Modernizr}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var A,B,l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}};B=function(a){function b(a){var e,f,g,a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a};for(f=0;d>f;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;b>f;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var c,b=0;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var m,n,h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var l,o,k=b.createElement("script"),e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var j,e=b.createElement("link"),c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))},function(global,undefined){"use strict";function addFromSetImmediateArguments(args){return tasksByHandle[nextHandle]=partiallyApplied.apply(undefined,args),nextHandle++}function partiallyApplied(handler){ var args=[].slice.call(arguments,1);return function(){"function"==typeof handler?handler.apply(undefined,args):new Function(""+handler)()}}function runIfPresent(handle){if(currentlyRunningATask)setTimeout(partiallyApplied(runIfPresent,handle),0);else{var task=tasksByHandle[handle];if(task){currentlyRunningATask=!0;try{task()}finally{clearImmediate(handle),currentlyRunningATask=!1}}}}function clearImmediate(handle){delete tasksByHandle[handle]}function installNextTickImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return process.nextTick(partiallyApplied(runIfPresent,handle)),handle}}function canUsePostMessage(){if(global.postMessage&&!global.importScripts){var postMessageIsAsynchronous=!0,oldOnMessage=global.onmessage;return global.onmessage=function(){postMessageIsAsynchronous=!1},global.postMessage("","*"),global.onmessage=oldOnMessage,postMessageIsAsynchronous}}function installPostMessageImplementation(){var messagePrefix="setImmediate$"+Math.random()+"$",onGlobalMessage=function(event){event.source===global&&"string"==typeof event.data&&0===event.data.indexOf(messagePrefix)&&runIfPresent(+event.data.slice(messagePrefix.length))};global.addEventListener?global.addEventListener("message",onGlobalMessage,!1):global.attachEvent("onmessage",onGlobalMessage),setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return global.postMessage(messagePrefix+handle,"*"),handle}}function installMessageChannelImplementation(){var channel=new MessageChannel;channel.port1.onmessage=function(event){var handle=event.data;runIfPresent(handle)},setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return channel.port2.postMessage(handle),handle}}function installReadyStateChangeImplementation(){var html=doc.documentElement;setImmediate=function(){var handle=addFromSetImmediateArguments(arguments),script=doc.createElement("script");return script.onreadystatechange=function(){runIfPresent(handle),script.onreadystatechange=null,html.removeChild(script),script=null},html.appendChild(script),handle}}function installSetTimeoutImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return setTimeout(partiallyApplied(runIfPresent,handle),0),handle}}if(!global.setImmediate){var setImmediate,nextHandle=1,tasksByHandle={},currentlyRunningATask=!1,doc=global.document,attachTo=Object.getPrototypeOf&&Object.getPrototypeOf(global);attachTo=attachTo&&attachTo.setTimeout?attachTo:global,"[object process]"==={}.toString.call(global.process)?installNextTickImplementation():canUsePostMessage()?installPostMessageImplementation():global.MessageChannel?installMessageChannelImplementation():doc&&"onreadystatechange"in doc.createElement("script")?installReadyStateChangeImplementation():installSetTimeoutImplementation(),attachTo.setImmediate=setImmediate,attachTo.clearImmediate=clearImmediate}}(function(){return this}()),function(){function Viewport(){return this.PRE_IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.DEFAULT_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.ensureViewportElement(),this.platform={},this.platform.name=this.getPlatformName(),this.platform.version=this.getPlatformVersion(),this}Viewport.prototype.ensureViewportElement=function(){this.viewportElement=document.querySelector("meta[name=viewport]"),this.viewportElement||(this.viewportElement=document.createElement("meta"),this.viewportElement.name="viewport",document.head.appendChild(this.viewportElement))},Viewport.prototype.setup=function(){function isWebView(){return!!(window.cordova||window.phonegap||window.PhoneGap)}this.viewportElement&&"true"!=this.viewportElement.getAttribute("data-no-adjust")&&("ios"==this.platform.name?this.platform.version>=7&&isWebView()?this.viewportElement.setAttribute("content",this.IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.PRE_IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.DEFAULT_VIEWPORT))},Viewport.prototype.getPlatformName=function(){return navigator.userAgent.match(/Android/i)?"android":navigator.userAgent.match(/iPhone|iPad|iPod/i)?"ios":void 0},Viewport.prototype.getPlatformVersion=function(){var start=window.navigator.userAgent.indexOf("OS ");return window.Number(window.navigator.userAgent.substr(start+3,3).replace("_","."))},window.Viewport=Viewport}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/back_button.tpl",'<span \n class="toolbar-button--quiet {{modifierTemplater(\'toolbar-button--*\')}}" \n ng-click="$root.ons.findParentComponentUntil(\'ons-navigator\', $event).popPage({cancelIfRunning: true})"\n ng-show="showBackButton"\n style="height: 44px; line-height: 0; padding: 0 10px 0 0; position: relative;">\n \n <i \n class="ion-ios-arrow-back ons-back-button__icon" \n style="vertical-align: top; background-color: transparent; height: 44px; line-height: 44px; font-size: 36px; margin-left: 8px; margin-right: 2px; width: 16px; display: inline-block; padding-top: 1px;"></i>\n\n <span \n style="vertical-align: top; display: inline-block; line-height: 44px; height: 44px;" \n class="back-button__label"></span>\n</span>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/button.tpl",'<span class="label ons-button-inner"></span>\n<span class="spinner button__spinner {{modifierTemplater(\'button--*__spinner\')}}"></span>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/dialog.tpl",'<div class="dialog-mask"></div>\n<div class="dialog {{ modifierTemplater(\'dialog--*\') }}"></div>\n</div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/icon.tpl",'<i class="fa fa-{{icon}} fa-{{spin}} fa-{{fixedWidth}} fa-rotate-{{rotate}} fa-flip-{{flip}}" ng-class="sizeClass" ng-style="style"></i>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/popover.tpl",'<div class="popover-mask"></div>\n<div class="popover popover--{{ direction }} {{ modifierTemplater(\'popover--*\') }}">\n <div class="popover__content {{ modifierTemplater(\'popover__content--*\') }}"></div>\n <div class="popover__{{ arrowPosition }}-arrow"></div>\n</div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/row.tpl",'<div class="row row-{{align}} ons-row-inner"></div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/sliding_menu.tpl",'<div class="onsen-sliding-menu__menu ons-sliding-menu-inner"></div>\n<div class="onsen-sliding-menu__main ons-sliding-menu-inner"></div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/split_view.tpl",'<div class="onsen-split-view__secondary full-screen ons-split-view-inner"></div>\n<div class="onsen-split-view__main full-screen ons-split-view-inner"></div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/switch.tpl",'<label class="switch {{modifierTemplater(\'switch--*\')}}">\n <input type="checkbox" class="switch__input {{modifierTemplater(\'switch--*__input\')}}" ng-model="model">\n <div class="switch__toggle {{modifierTemplater(\'switch--*__toggle\')}}"></div>\n</label>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/tab.tpl",'<input type="radio" name="tab-bar-{{tabbarId}}" style="display: none">\n<button class="tab-bar__button tab-bar-inner {{tabbarModifierTemplater(\'tab-bar--*__button\')}} {{modifierTemplater(\'tab-bar__button--*\')}}" ng-click="tryToChange()">\n</button>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/tab_bar.tpl",'<div class="ons-tab-bar__content tab-bar__content"></div>\n<div ng-hide="hideTabs" class="tab-bar ons-tab-bar__footer {{modifierTemplater(\'tab-bar--*\')}} ons-tabbar-inner"></div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/toolbar_button.tpl","<span class=\"toolbar-button {{modifierTemplater('toolbar-button--*')}} navigation-bar__line-height\" ng-transclude></span>\n")}])}(),window.DoorLock=function(){var DoorLock=function(options){options=options||{},this._lockList=[],this._waitList=[],this._log=options.log||function(){}};return DoorLock.generateId=function(){var i=0;return function(){return i++}}(),DoorLock.prototype={lock:function(){var self=this,unlock=function(){self._unlock(unlock)};return unlock.id=DoorLock.generateId(),this._lockList.push(unlock),this._log("lock: "+unlock.id),unlock},_unlock:function(fn){var index=this._lockList.indexOf(fn);if(-1===index)throw new Error("This function is not registered in the lock list.");this._lockList.splice(index,1),this._log("unlock: "+fn.id),this._tryToFreeWaitList()},_tryToFreeWaitList:function(){for(;!this.isLocked()&&this._waitList.length>0;)this._waitList.shift()()},waitUnlock:function(callback){if(!(callback instanceof Function))throw new Error("The callback param must be a function.");this.isLocked()?this._waitList.push(callback):callback()},isLocked:function(){return this._lockList.length>0}},DoorLock}(),window.ons=function(){"use strict";function waitDeviceReady(){var unlockDeviceReady=ons._readyLock.lock();window.addEventListener("DOMContentLoaded",function(){ons.isWebView()?window.document.addEventListener("deviceready",unlockDeviceReady,!1):unlockDeviceReady()},!1)}function waitOnsenUILoad(){var unlockOnsenUI=ons._readyLock.lock();module.run(["$compile","$rootScope","$onsen",function($compile,$rootScope,$onsen){if("loading"===document.readyState||"uninitialized"==document.readyState)window.addEventListener("DOMContentLoaded",function(){document.body.appendChild(document.createElement("ons-dummy-for-init"))});else{if(!document.body)throw new Error("Invalid initialization state.");document.body.appendChild(document.createElement("ons-dummy-for-init"))}$rootScope.$on("$ons-ready",unlockOnsenUI)}])}function initAngularModule(){module.value("$onsGlobal",ons),module.run(["$compile","$rootScope","$onsen","$q",function($compile,$rootScope,$onsen,$q){ons._onsenService=$onsen,ons._qService=$q,$rootScope.ons=window.ons,$rootScope.console=window.console,$rootScope.alert=window.alert,ons.$compile=$compile}])}function initKeyboardEvents(){ons.softwareKeyboard=new MicroEvent,ons.softwareKeyboard._visible=!1;var onShow=function(){ons.softwareKeyboard._visible=!0,ons.softwareKeyboard.emit("show")},onHide=function(){ons.softwareKeyboard._visible=!1,ons.softwareKeyboard.emit("hide")},bindEvents=function(){return"undefined"!=typeof Keyboard?(Keyboard.onshow=onShow,Keyboard.onhide=onHide,ons.softwareKeyboard.emit("init",{visible:Keyboard.isVisible}),!0):"undefined"!=typeof cordova.plugins&&"undefined"!=typeof cordova.plugins.Keyboard?(window.addEventListener("native.keyboardshow",onShow),window.addEventListener("native.keyboardhide",onHide),ons.softwareKeyboard.emit("init",{visible:cordova.plugins.Keyboard.isVisible}),!0):!1},noPluginError=function(){console.warn("ons-keyboard: Cordova Keyboard plugin is not present.")};document.addEventListener("deviceready",function(){bindEvents()||((document.querySelector("[ons-keyboard-active]")||document.querySelector("[ons-keyboard-inactive]"))&&noPluginError(),ons.softwareKeyboard.on=noPluginError)})}function createOnsenFacade(){var ons={_readyLock:new DoorLock,_onsenService:null,_config:{autoStatusBarFill:!0},_unlockersDict:{},componentBase:window,bootstrap:function(name,deps){angular.isArray(name)&&(deps=name,name=void 0),name||(name="myOnsenApp"),deps=["onsen"].concat(angular.isArray(deps)?deps:[]);var module=angular.module(name,deps),doc=window.document;if("loading"==doc.readyState||"uninitialized"==doc.readyState||"interactive"==doc.readyState)doc.addEventListener("DOMContentLoaded",function(){angular.bootstrap(doc.documentElement,[name])},!1);else{if(!doc.documentElement)throw new Error("Invalid state");angular.bootstrap(doc.documentElement,[name])}return module},enableAutoStatusBarFill:function(){if(this.isReady())throw new Error("This method must be called before ons.isReady() is true.");this._config.autoStatusBarFill=!0},disableAutoStatusBarFill:function(){if(this.isReady())throw new Error("This method must be called before ons.isReady() is true.");this._config.autoStatusBarFill=!1},findParentComponentUntil:function(name,dom){var element;return dom instanceof HTMLElement?element=angular.element(dom):dom instanceof angular.element?element=dom:dom.target&&(element=angular.element(dom.target)),element.inheritedData(name)},setDefaultDeviceBackButtonListener:function(listener){this._getOnsenService().getDefaultDeviceBackButtonHandler().setListener(listener)},disableDeviceBackButtonHandler:function(){this._getOnsenService().DeviceBackButtonHandler.disable()},enableDeviceBackButtonHandler:function(){this._getOnsenService().DeviceBackButtonHandler.enable()},findComponent:function(selector,dom){var target=(dom?dom:document).querySelector(selector);return target?angular.element(target).data(target.nodeName.toLowerCase())||null:null},isReady:function(){return!ons._readyLock.isLocked()},compile:function(dom){if(!ons.$compile)throw new Error("ons.$compile() is not ready. Wait for initialization with ons.ready().");if(!(dom instanceof HTMLElement))throw new Error("First argument must be an instance of HTMLElement.");var scope=angular.element(dom).scope();if(!scope)throw new Error("AngularJS Scope is null. Argument DOM element must be attached in DOM document.");ons.$compile(dom)(scope)},_getOnsenService:function(){if(!this._onsenService)throw new Error("$onsen is not loaded, wait for ons.ready().");return this._onsenService},ready:function(callback){if(callback instanceof Function)ons.isReady()?callback():ons._readyLock.waitUnlock(callback);else if(angular.isArray(callback)&&arguments[1]instanceof Function){var dependencies=callback;callback=arguments[1],ons.ready(function(){var $onsen=ons._getOnsenService();$onsen.waitForVariables(dependencies,callback)})}},isWebView:function(){if("loading"===document.readyState||"uninitialized"==document.readyState)throw new Error("isWebView() method is available after dom contents loaded.");return!!(window.cordova||window.phonegap||window.PhoneGap)},createAlertDialog:function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");var alertDialog=angular.element("<ons-alert-dialog>"),$onsen=this._getOnsenService();return angular.element(document.body).append(angular.element(alertDialog)),$onsen.getPageHTMLAsync(page).then(function(html){var div=document.createElement("div");div.innerHTML=html;for(var el=angular.element(div.querySelector("ons-alert-dialog")),attrs=el.prop("attributes"),i=0,l=attrs.length;l>i;i++)alertDialog.attr(attrs[i].name,attrs[i].value);alertDialog.html(el.html());var parentScope;return options.parentScope?(parentScope=options.parentScope.$new(),ons.$compile(alertDialog)(parentScope)):ons.compile(alertDialog[0]),el.attr("disabled")&&alertDialog.attr("disabled","disabled"),parentScope&&(alertDialog.data("ons-alert-dialog")._parentScope=parentScope),alertDialog.data("ons-alert-dialog")})},createDialog:function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");var dialog=angular.element("<ons-dialog>"),$onsen=this._getOnsenService();return angular.element(document.body).append(angular.element(dialog)),$onsen.getPageHTMLAsync(page).then(function(html){var div=document.createElement("div");div.innerHTML=html;for(var el=angular.element(div.querySelector("ons-dialog")),attrs=el.prop("attributes"),i=0,l=attrs.length;l>i;i++)dialog.attr(attrs[i].name,attrs[i].value);dialog.html(el.html());var parentScope;options.parentScope?(parentScope=options.parentScope.$new(),ons.$compile(dialog)(parentScope)):ons.compile(dialog[0]),el.attr("disabled")&&dialog.attr("disabled","disabled");var deferred=ons._qService.defer();return dialog.on("ons-dialog:init",function(e){var child=dialog[0].querySelector(".dialog");if(el[0].hasAttribute("style")){var parentStyle=el[0].getAttribute("style"),childStyle=child.getAttribute("style"),newStyle=function(a,b){var c=(";"===a.substr(-1)?a:a+";")+(";"===b.substr(-1)?b:b+";");return c}(parentStyle,childStyle);child.setAttribute("style",newStyle)}parentScope&&(e.component._parentScope=parentScope),deferred.resolve(e.component)}),deferred.promise})},createPopover:function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");var popover=angular.element("<ons-popover>"),$onsen=this._getOnsenService();return angular.element(document.body).append(angular.element(popover)),$onsen.getPageHTMLAsync(page).then(function(html){var div=document.createElement("div");div.innerHTML=html;for(var el=angular.element(div.querySelector("ons-popover")),attrs=el.prop("attributes"),i=0,l=attrs.length;l>i;i++)popover.attr(attrs[i].name,attrs[i].value);popover.html(el.html());var parentScope;options.parentScope?(parentScope=options.parentScope.$new(),ons.$compile(popover)(parentScope)):ons.compile(popover[0]),el.attr("disabled")&&popover.attr("disabled","disabled");var deferred=ons._qService.defer();return popover.on("ons-popover:init",function(e){var child=popover[0].querySelector(".popover");if(el[0].hasAttribute("style")){var parentStyle=el[0].getAttribute("style"),childStyle=child.getAttribute("style"),newStyle=function(a,b){var c=(";"===a.substr(-1)?a:a+";")+(";"===b.substr(-1)?b:b+";");return c}(parentStyle,childStyle);child.setAttribute("style",newStyle)}parentScope&&(e.component._parentScope=parentScope),deferred.resolve(e.component)}),deferred.promise})}};return ons}var module=angular.module("onsen",["templates-main"]);angular.module("onsen.directives",["onsen"]);var ons=createOnsenFacade();return initKeyboardEvents(),waitDeviceReady(),waitOnsenUILoad(),initAngularModule(),ons}(),function(){"use strict";var module=angular.module("onsen");module.factory("AlertDialogView",["$onsen","DialogAnimator","SlideDialogAnimator","AndroidAlertDialogAnimator","IOSAlertDialogAnimator",function($onsen,DialogAnimator,SlideDialogAnimator,AndroidAlertDialogAnimator,IOSAlertDialogAnimator){var AlertDialogView=Class.extend({init:function(scope,element,attrs){if(this._scope=scope,this._element=element,this._attrs=attrs,this._element.css({display:"none",zIndex:20001}),this._dialog=element,this._visible=!1,this._doorLock=new DoorLock,this._animation=AlertDialogView._animatorDict["undefined"!=typeof attrs.animation?attrs.animation:"default"],!this._animation)throw new Error("No such animation: "+attrs.animation);this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._createMask(attrs.maskColor),this._scope.$on("$destroy",this._destroy.bind(this))},show:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("preshow",{alertDialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;this._mask.css("display","block"),this._mask.css("opacity",1),this._element.css("display","block"),options.animation&&(animation=AlertDialogView._animatorDict[options.animation]),animation.show(this,function(){this._visible=!0,unlock(),this.emit("postshow",{alertDialog:this}),callback()}.bind(this))}.bind(this))},hide:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("prehide",{alertDialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;options.animation&&(animation=AlertDialogView._animatorDict[options.animation]),animation.hide(this,function(){this._element.css("display","none"),this._mask.css("display","none"),this._visible=!1,unlock(),this.emit("posthide",{alertDialog:this}),callback()}.bind(this))}.bind(this))},isShown:function(){return this._visible},destroy:function(){this._parentScope?(this._parentScope.$destroy(),this._parentScope=null):this._scope.$destroy()},_destroy:function(){this.emit("destroy"),this._mask.off(),this._element.remove(),this._mask.remove(),this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=this._scope=this._attrs=this._element=this._mask=null},setDisabled:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this._element.attr("disabled",!0):this._element.removeAttr("disabled")},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setCancelable:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this._element.attr("cancelable",!0):this._element.removeAttr("cancelable")},isCancelable:function(){return this._element[0].hasAttribute("cancelable")},_cancel:function(){this.isCancelable()&&this.hide({callback:function(){this.emit("cancel")}.bind(this)})},_onDeviceBackButton:function(event){this.isCancelable()?this._cancel.bind(this)():event.callParentHandler()},_createMask:function(color){this._mask=angular.element("<div>").addClass("alert-dialog-mask").css({zIndex:2e4,display:"none"}),this._mask.on("click",this._cancel.bind(this)),color&&this._mask.css("background-color",color),angular.element(document.body).append(this._mask)}});return AlertDialogView._animatorDict={"default":$onsen.isAndroid()?new AndroidAlertDialogAnimator:new IOSAlertDialogAnimator,fade:$onsen.isAndroid()?new AndroidAlertDialogAnimator:new IOSAlertDialogAnimator,slide:new SlideDialogAnimator,none:new DialogAnimator},AlertDialogView.registerAnimator=function(name,animator){if(!(animator instanceof DialogAnimator))throw new Error('"animator" param must be an instance of DialogAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(AlertDialogView),AlertDialogView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("AndroidAlertDialogAnimator",["DialogAnimator",function(DialogAnimator){var AndroidAlertDialogAnimator=DialogAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return AndroidAlertDialogAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("AndroidDialogAnimator",["DialogAnimator",function(DialogAnimator){var AndroidDialogAnimator=DialogAnimator.extend({timing:"ease-in-out",duration:.3,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return AndroidDialogAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("ButtonView",["$onsen",function($onsen){var ButtonView=Class.extend({init:function(scope,element,attrs){this._element=element,this._scope=scope,this._attrs=attrs},startSpin:function(){this._attrs.$set("shouldSpin","true")},stopSpin:function(){this._attrs.$set("shouldSpin","false")},isSpinning:function(){return"true"===this._attrs.shouldSpin},setSpinAnimation:function(animation){this._scope.$apply(function(){var animations=["slide-left","slide-right","slide-up","slide-down","expand-left","expand-right","expand-up","expand-down","zoom-out","zoom-in"];animations.indexOf(animation)<0&&(console.warn("Animation "+animation+"doesn't exist."),animation="slide-left"),this._scope.animation=animation}.bind(this))},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setDisabled:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this._element[0].setAttribute("disabled",""):this._element[0].removeAttribute("disabled")}});return MicroEvent.mixin(ButtonView),ButtonView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("CarouselView",["$onsen",function($onsen){var VerticalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaY},_getScrollVelocity:function(event){return event.gesture.velocityY},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this._element[0].getBoundingClientRect().height),this._currentElementSize},_generateScrollTransform:function(scroll){return"translate3d(0px, "+-scroll+"px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),i=0;i<children.length;i++)angular.element(children[i]).css({position:"absolute",height:sizeAttr,width:"100%",visibility:"visible",left:"0px",top:i*sizeInfo.number+sizeInfo.unit})}},HorizontalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaX},_getScrollVelocity:function(event){return event.gesture.velocityX},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this._element[0].getBoundingClientRect().width),this._currentElementSize},_generateScrollTransform:function(scroll){return"translate3d("+-scroll+"px, 0px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),i=0;i<children.length;i++)angular.element(children[i]).css({position:"absolute",width:sizeAttr,height:"100%",top:"0px",visibility:"visible",left:i*sizeInfo.number+sizeInfo.unit})}},CarouselView=Class.extend({_element:void 0,_scope:void 0,_doorLock:void 0,_scroll:void 0,init:function(scope,element,attrs){this._element=element,this._scope=scope,this._attrs=attrs,this._doorLock=new DoorLock,this._scroll=0,this._lastActiveIndex=0,this._bindedOnDrag=this._onDrag.bind(this),this._bindedOnDragEnd=this._onDragEnd.bind(this),this._bindedOnResize=this._onResize.bind(this),this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._prepareEventListeners(),this._layoutCarouselItems(),this._setupInitialIndex(),this._attrs.$observe("direction",this._onDirectionChange.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this)),this._saveLastState()},_onResize:function(){this.refresh()},_onDirectionChange:function(){this._isVertical()?this._element.css({overflowX:"auto",overflowY:""}):this._element.css({overflowX:"",overflowY:"auto"})},_saveLastState:function(){this._lastState={elementSize:this._getCarouselItemSize(),carouselElementCount:this._getCarouselItemCount(),width:this._getCarouselItemSize()*this._getCarouselItemCount()}},_getCarouselItemSize:function(){var sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),elementSize=this._getElementSize();if("%"===sizeInfo.unit)return Math.round(sizeInfo.number/100*elementSize);if("px"===sizeInfo.unit)return sizeInfo.number;throw new Error("Invalid state")},_getInitialIndex:function(){var index=parseInt(this._element.attr("initial-index"),10);return"number"!=typeof index||isNaN(index)?0:Math.max(Math.min(index,this._getCarouselItemCount()-1),0)},_getCarouselItemSizeAttr:function(){var attrName="item-"+(this._isVertical()?"height":"width"),itemSizeAttr=(""+this._element.attr(attrName)).trim();return itemSizeAttr.match(/^\d+(px|%)$/)?itemSizeAttr:"100%"},_decomposeSizeString:function(size){var matches=size.match(/^(\d+)(px|%)/);return{number:parseInt(matches[1],10),unit:matches[2]}},_setupInitialIndex:function(){this._scroll=this._getCarouselItemSize()*this._getInitialIndex(),this._lastActiveIndex=this._getInitialIndex(),this._scrollTo(this._scroll)},setSwipeable:function(swipeable){swipeable?this._element[0].setAttribute("swipeable",""):this._element[0].removeAttribute("swipeable")},isSwipeable:function(){return this._element[0].hasAttribute("swipeable")},setAutoScrollRatio:function(ratio){if(0>ratio||ratio>1)throw new Error("Invalid ratio.");this._element[0].setAttribute("auto-scroll-ratio",ratio)},getAutoScrollRatio:function(ratio){var attr=this._element[0].getAttribute("auto-scroll-ratio");if(!attr)return.5;var scrollRatio=parseFloat(attr);if(0>scrollRatio||scrollRatio>1)throw new Error("Invalid ratio.");return isNaN(scrollRatio)?.5:scrollRatio},setActiveCarouselItemIndex:function(index,options){options=options||{},index=Math.max(0,Math.min(index,this._getCarouselItemCount()-1));var scroll=this._getCarouselItemSize()*index,max=this._calculateMaxScroll(); this._scroll=Math.max(0,Math.min(max,scroll)),this._scrollTo(this._scroll,{animate:"none"!==options.animation,callback:options.callback}),this._tryFirePostChangeEvent()},getActiveCarouselItemIndex:function(){var scroll=this._scroll,count=this._getCarouselItemCount(),size=this._getCarouselItemSize();if(0>scroll)return 0;for(var i=0;count>i;i++)if(scroll>=size*i&&size*(i+1)>scroll)return i;return i},next:function(options){this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()+1,options)},prev:function(options){this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()-1,options)},setAutoScrollEnabled:function(enabled){enabled?this._element[0].setAttribute("auto-scroll",""):this._element[0].removeAttribute("auto-scroll")},isAutoScrollEnabled:function(enabled){return this._element[0].hasAttribute("auto-scroll")},setDisabled:function(disabled){disabled?this._element[0].setAttribute("disabled",""):this._element[0].removeAttribute("disabled")},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setOverscrollable:function(scrollable){scrollable?this._element[0].setAttribute("overscrollable",""):this._element[0].removeAttribute("overscrollable")},_mixin:function(trait){Object.keys(trait).forEach(function(key){this[key]=trait[key]}.bind(this))},_isEnabledChangeEvent:function(){var elementSize=this._getElementSize(),carouselItemSize=this._getCarouselItemSize();return this.isAutoScrollEnabled()&&elementSize===carouselItemSize},_isVertical:function(){return"vertical"===this._element.attr("direction")},_prepareEventListeners:function(){this._hammer=new Hammer(this._element[0],{dragMinDistance:1}),this._hammer.on("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._bindedOnDrag),this._hammer.on("dragend",this._bindedOnDragEnd),angular.element(window).on("resize",this._bindedOnResize)},_tryFirePostChangeEvent:function(){var currentIndex=this.getActiveCarouselItemIndex();if(this._lastActiveIndex!==currentIndex){var lastActiveIndex=this._lastActiveIndex;this._lastActiveIndex=currentIndex,this.emit("postchange",{carousel:this,activeIndex:currentIndex,lastActiveIndex:lastActiveIndex})}},_onDrag:function(event){if(this.isSwipeable()){var direction=event.gesture.direction;if((!this._isVertical()||"left"!==direction&&"right"!==direction)&&(this._isVertical()||"up"!==direction&&"down"!==direction)){event.stopPropagation(),this._lastDragEvent=event;var scroll=this._scroll-this._getScrollDelta(event);this._scrollTo(scroll),event.gesture.preventDefault(),this._tryFirePostChangeEvent()}}},_onDragEnd:function(event){if(this._currentElementSize=void 0,this._carouselItemElements=void 0,this.isSwipeable()){if(this._scroll=this._scroll-this._getScrollDelta(event),0!==this._getScrollDelta(event)&&event.stopPropagation(),this._isOverScroll(this._scroll)){var waitForAction=!1;this.emit("overscroll",{carousel:this,activeIndex:this.getActiveCarouselItemIndex(),direction:this._getOverScrollDirection(),waitToReturn:function(promise){waitForAction=!0,promise.then(function(){this._scrollToKillOverScroll()}.bind(this))}.bind(this)}),waitForAction||this._scrollToKillOverScroll()}else this._startMomemtumScroll(event);this._lastDragEvent=null,event.gesture.preventDefault()}},_getTouchEvents:function(){var EVENTS=["drag","dragstart","dragend","dragup","dragdown","dragleft","dragright","swipe","swipeup","swipedown","swipeleft","swiperight"];return EVENTS.join(" ")},isOverscrollable:function(){return this._element[0].hasAttribute("overscrollable")},_startMomemtumScroll:function(event){if(this._lastDragEvent){var velocity=this._getScrollVelocity(this._lastDragEvent),duration=.3,scrollDelta=100*duration*velocity,scroll=this._scroll+(this._getScrollDelta(this._lastDragEvent)>0?-scrollDelta:scrollDelta);scroll=this._normalizeScrollPosition(scroll),this._scroll=scroll,animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(this._scroll)},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play()}},_normalizeScrollPosition:function(scroll){var max=this._calculateMaxScroll();if(this.isAutoScrollEnabled()){for(var arr=[],size=this._getCarouselItemSize(),i=0;i<this._getCarouselItemCount();i++)max>=i*size&&arr.push(i*size);arr.push(max),arr.sort(function(left,right){return left=Math.abs(left-scroll),right=Math.abs(right-scroll),left-right}),arr=arr.filter(function(item,pos){return!pos||item!=arr[pos-1]});var lastScroll=this._lastActiveIndex*size,scrollRatio=Math.abs(scroll-lastScroll)/size;return scrollRatio<=this.getAutoScrollRatio()?lastScroll:scrollRatio>this.getAutoScrollRatio()&&1>scrollRatio&&arr[0]===lastScroll&&arr.length>1?arr[1]:arr[0]}return Math.max(0,Math.min(max,scroll))},_getCarouselItemElements:function(){for(var nodeList=this._element[0].children,rv=[],i=nodeList.length;i--;)rv.unshift(nodeList[i]);return rv=rv.filter(function(item){return"ons-carousel-item"===item.nodeName.toLowerCase()})},_scrollTo:function(scroll,options){function normalizeScroll(scroll){var ratio=.35;if(0>scroll)return isOverscrollable?Math.round(scroll*ratio):0;var maxScroll=self._calculateMaxScroll();return scroll>maxScroll?isOverscrollable?maxScroll+Math.round((scroll-maxScroll)*ratio):maxScroll:scroll}options=options||{};var self=this,isOverscrollable=this.isOverscrollable();options.animate?animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(options.callback):animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))}).play(options.callback)},_calculateMaxScroll:function(){var max=this._getCarouselItemCount()*this._getCarouselItemSize()-this._getElementSize();return Math.ceil(0>max?0:max)},_isOverScroll:function(scroll){return 0>scroll||scroll>this._calculateMaxScroll()?!0:!1},_getOverScrollDirection:function(){return this._isVertical()?this._scroll<=0?"up":"down":this._scroll<=0?"left":"right"},_scrollToKillOverScroll:function(){var duration=.4;if(this._scroll<0)return animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(0)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play(),void(this._scroll=0);var maxScroll=this._calculateMaxScroll();return maxScroll<this._scroll?(animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(maxScroll)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play(),void(this._scroll=maxScroll)):void 0},_getCarouselItemCount:function(){return this._getCarouselItemElements().length},refresh:function(){if(0!==this._getCarouselItemSize()){if(this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._lastState&&this._lastState.width>0){var scroll=this._scroll;this._isOverScroll(scroll)?this._scrollToKillOverScroll():(this.isAutoScrollEnabled()&&(scroll=this._normalizeScrollPosition(scroll)),this._scrollTo(scroll))}this._saveLastState(),this.emit("refresh",{carousel:this})}},first:function(){this.setActiveCarouselItemIndex(0)},last:function(){this.setActiveCarouselItemIndex(Math.max(this._getCarouselItemCount()-1,0))},_destroy:function(){this.emit("destroy"),this._hammer.off("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._bindedOnDrag),this._hammer.off("dragend",this._bindedOnDragEnd),angular.element(window).off("resize",this._bindedOnResize),this._element=this._scope=this._attrs=null}});return MicroEvent.mixin(CarouselView),CarouselView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("DialogView",["$onsen","DialogAnimator","IOSDialogAnimator","AndroidDialogAnimator","SlideDialogAnimator",function($onsen,DialogAnimator,IOSDialogAnimator,AndroidDialogAnimator,SlideDialogAnimator){var DialogView=Class.extend({init:function(scope,element,attrs){if(this._scope=scope,this._element=element,this._attrs=attrs,this._element.css("display","none"),this._dialog=angular.element(element[0].querySelector(".dialog")),this._mask=angular.element(element[0].querySelector(".dialog-mask")),this._dialog.css("z-index",20001),this._mask.css("z-index",2e4),this._mask.on("click",this._cancel.bind(this)),this._visible=!1,this._doorLock=new DoorLock,this._animation=DialogView._animatorDict["undefined"!=typeof attrs.animation?attrs.animation:"default"],!this._animation)throw new Error("No such animation: "+attrs.animation);this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this))},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},_getMaskColor:function(){return this._element[0].getAttribute("mask-color")||"rgba(0, 0, 0, 0.2)"},show:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("preshow",{dialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;this._element.css("display","block"),this._mask.css("opacity",1),this._mask.css("backgroundColor",this._getMaskColor()),options.animation&&(animation=DialogView._animatorDict[options.animation]),animation.show(this,function(){this._visible=!0,unlock(),this.emit("postshow",{dialog:this}),callback()}.bind(this))}.bind(this))},hide:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("prehide",{dialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;options.animation&&(animation=DialogView._animatorDict[options.animation]),animation.hide(this,function(){this._element.css("display","none"),this._visible=!1,unlock(),this.emit("posthide",{dialog:this}),callback()}.bind(this))}.bind(this))},isShown:function(){return this._visible},destroy:function(){this._parentScope?(this._parentScope.$destroy(),this._parentScope=null):this._scope.$destroy()},_destroy:function(){this.emit("destroy"),this._element.remove(),this._deviceBackButtonHandler.destroy(),this._mask.off(),this._deviceBackButtonHandler=this._scope=this._attrs=this._element=this._dialog=this._mask=null},setDisabled:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this._element.attr("disabled",!0):this._element.removeAttr("disabled")},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setCancelable:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this._element.attr("cancelable",!0):this._element.removeAttr("cancelable")},isCancelable:function(){return this._element[0].hasAttribute("cancelable")},_cancel:function(){this.isCancelable()&&this.hide({callback:function(){this.emit("cancel")}.bind(this)})},_onDeviceBackButton:function(event){this.isCancelable()?this._cancel.bind(this)():event.callParentHandler()}});return DialogView._animatorDict={"default":$onsen.isAndroid()?new AndroidDialogAnimator:new IOSDialogAnimator,fade:$onsen.isAndroid()?new AndroidDialogAnimator:new IOSDialogAnimator,slide:new SlideDialogAnimator,none:new DialogAnimator},DialogView.registerAnimator=function(name,animator){if(!(animator instanceof DialogAnimator))throw new Error('"animator" param must be an instance of DialogAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(DialogView),DialogView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("DialogAnimator",function(){var DialogAnimator=Class.extend({show:function(dialog,callback){callback()},hide:function(dialog,callback){callback()}});return DialogAnimator})}(),function(){"use strict";var module=angular.module("onsen");module.factory("FadePopoverAnimator",["PopoverAnimator",function(PopoverAnimator){var FadePopoverAnimator=PopoverAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(popover,callback){var pop=popover._element[0].querySelector(".popover"),mask=popover._element[0].querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(pop).queue({transform:"scale3d(1.3, 1.3, 1.0)",opacity:0}).queue({transform:"scale3d(1.0, 1.0, 1.0)",opacity:1},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(popover,callback){var pop=popover._element[0].querySelector(".popover"),mask=popover._element[0].querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(pop).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return FadePopoverAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("FadeTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var FadeTransitionAnimator=NavigatorTransitionAnimator.extend({push:function(enterPage,leavePage,callback){animit.runAll(animit([enterPage.getPageView().getContentElement(),enterPage.getPageView().getBackgroundElement()]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:.4,timing:"linear"}).resetStyle().queue(function(done){callback(),done()}),animit(enterPage.getPageView().getToolbarElement()).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:.4,timing:"linear"}).resetStyle())},pop:function(enterPage,leavePage,callback){animit.runAll(animit([leavePage.getPageView().getContentElement(),leavePage.getPageView().getBackgroundElement()]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:.4,timing:"linear"}).queue(function(done){callback(),done()}),animit(leavePage.getPageView().getToolbarElement()).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:.4,timing:"linear"}))}});return FadeTransitionAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("GenericView",["$onsen",function($onsen){var GenericView=Class.extend({init:function(scope,element,attrs){this._element=element,this._scope=scope}});return MicroEvent.mixin(GenericView),GenericView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("IOSAlertDialogAnimator",["DialogAnimator",function(DialogAnimator){var IOSAlertDialogAnimator=DialogAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.3, 1.3, 1.0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{opacity:1},duration:0}).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return IOSAlertDialogAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("IOSDialogAnimator",["DialogAnimator",function(DialogAnimator){var IOSDialogAnimator=DialogAnimator.extend({timing:"ease-in-out",duration:.3,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:0}).queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return IOSDialogAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("IOSSlideTransitionAnimator",["NavigatorTransitionAnimator","PageView",function(NavigatorTransitionAnimator,PageView){var IOSSlideTransitionAnimator=NavigatorTransitionAnimator.extend({backgroundMask:angular.element('<div style="position: absolute; width: 100%;height: 100%; background-color: black; opacity: 0;"></div>'),_decompose:function(page){function excludeBackButtonLabel(elements){for(var result=[],i=0;i<elements.length;i++)"ons-back-button"===elements[i].nodeName.toLowerCase()?result.push(elements[i].querySelector(".ons-back-button__icon")):result.push(elements[i]);return result}var left=page.getPageView().getToolbarLeftItemsElement(),right=page.getPageView().getToolbarRightItemsElement(),other=[].concat(0===left.children.length?left:excludeBackButtonLabel(left.children)).concat(0===right.children.length?right:excludeBackButtonLabel(right.children)),pageLabels=[page.getPageView().getToolbarCenterItemsElement(),page.getPageView().getToolbarBackButtonLabelElement()];return{pageLabels:pageLabels,other:other,content:page.getPageView().getContentElement(),background:page.getPageView().getBackgroundElement(),toolbar:page.getPageView().getToolbarElement(),bottomToolbar:page.getPageView().getBottomToolbarElement()}},_shouldAnimateToolbar:function(enterPage,leavePage){var bothPageHasToolbar=enterPage.getPageView().hasToolbarElement()&&leavePage.getPageView().hasToolbarElement(),noAndroidLikeToolbar=!angular.element(enterPage.getPageView().getToolbarElement()).hasClass("navigation-bar--android")&&!angular.element(leavePage.getPageView().getToolbarElement()).hasClass("navigation-bar--android");return bothPageHasToolbar&&noAndroidLikeToolbar},push:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();leavePage.element[0].parentNode.insertBefore(mask[0],leavePage.element[0].nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element[0].getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(mask[0]).queue({opacity:0,transform:"translate3d(0, 0, 0)"}).queue({opacity:.1},{duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){mask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.css({zIndex:"auto"}),leavePage.element.css({zIndex:"auto"}),animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.toolbar).queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}).wait(.3).resetStyle({duration:.1,transition:"background-color 0.1s linear, border-color 0.1s linear"}),animit(enterPageDecomposition.pageLabels).queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.other).queue({css:{opacity:0},duration:0}).queue({css:{opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){enterPage.element.css({zIndex:""}),leavePage.element.css({zIndex:""}),callback(),done()}),animit(leavePageDecomposition.pageLabels).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(leavePageDecomposition.other).queue({css:{opacity:1},duration:0}).queue({css:{opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle())):animit.runAll(maskClear,animit(enterPage.element[0]).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){callback(),done()}))},pop:function(enterPage,leavePage,done){var mask=this.backgroundMask.remove();enterPage.element[0].parentNode.insertBefore(mask[0],enterPage.element[0].nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element[0].getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(mask[0]).queue({opacity:.1,transform:"translate3d(0, 0, 0)"}).queue({opacity:0},{duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){mask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.css({zIndex:"auto"}),leavePage.element.css({zIndex:"auto"}),animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.pageLabels).queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.toolbar).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.other).queue({css:{opacity:0},duration:0}).queue({css:{opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).wait(0).queue(function(finish){enterPage.element.css({zIndex:""}),leavePage.element.css({zIndex:""}),done(),finish()}),animit(leavePageDecomposition.other).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}),animit(leavePageDecomposition.toolbar).queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}),animit(leavePageDecomposition.pageLabels).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}))):animit.runAll(maskClear,animit(enterPage.element[0]).queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(finish){done(),finish()}))}});return IOSSlideTransitionAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("LazyRepeatView",["$onsen","$document","$compile",function($onsen,$document,$compile){var LazyRepeatView=Class.extend({init:function(scope,element,attrs,linker){if(this._element=element,this._scope=scope,this._attrs=attrs,this._linker=linker,this._parentElement=element.parent(),this._pageContent=this._findPageContent(),!this._pageContent)throw new Error("ons-lazy-repeat must be a descendant of an <ons-page> or an <ons-scroller> element.");this._itemHeightSum=[],this._maxIndex=0,this._delegate=this._getDelegate(),this._renderedElements={},this._addEventListeners(),this._scope.$watch(this._countItems.bind(this),this._onChange.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this)),this._onChange()},_getDelegate:function(){var delegate=this._scope.$eval(this._attrs.onsLazyRepeat);return"undefined"==typeof delegate&&(delegate=eval(this._attrs.onsLazyRepeat)),delegate},_countItems:function(){return this._delegate.countItems()},_getItemHeight:function(i){return this._delegate.calculateItemHeight(i)},_getTopOffset:function(){return this._parentElement[0].getBoundingClientRect().top},_render:function(){var items=this._getItemsInView(),keep={};this._parentElement.css("height",this._itemHeightSum[this._maxIndex]+"px");for(var i=0,l=items.length;l>i;i++){var _item=items[i];this._renderElement(_item),keep[_item.index]=!0}for(var key in this._renderedElements)this._renderedElements.hasOwnProperty(key)&&!keep.hasOwnProperty(key)&&this._removeElement(key)},_isRendered:function(i){return this._renderedElements.hasOwnProperty(i)},_renderElement:function(item){if(this._isRendered(item.index)){var currentItem=this._renderedElements[item.index];this._delegate.configureItemScope&&this._delegate.configureItemScope(item.index,currentItem.scope);var element=this._renderedElements[item.index].element;return void(element[0].style.top=item.top+"px")}var childScope=this._scope.$new();this._addSpecialProperties(item.index,childScope),this._linker(childScope,function(clone){this._delegate.configureItemScope?this._delegate.configureItemScope(item.index,childScope):this._delegate.createItemContent&&(clone.append(this._delegate.createItemContent(item.index)),$compile(clone[0].firstChild)(childScope)),this._parentElement.append(clone),clone.css({position:"absolute",top:item.top+"px",left:"0px",right:"0px",display:"none"});var element={element:clone,scope:childScope};this._scope.$evalAsync(function(){clone.css("display","block")}),this._renderedElements[item.index]=element}.bind(this))},_removeElement:function(i){if(this._isRendered(i)){var element=this._renderedElements[i];this._delegate.destroyItemScope?this._delegate.destroyItemScope(i,element.scope):this._delegate.destroyItemContent&&this._delegate.destroyItemContent(i,element.element.children()[0]),element.element.remove(),element.scope.$destroy(),element.element=element.scope=null,delete this._renderedElements[i]}},_removeAllElements:function(){for(var key in this._renderedElements)this._removeElement.hasOwnProperty(key)&&this._removeElement(key)},_calculateStartIndex:function(current){for(var start=0,end=this._maxIndex;;){var middle=Math.floor((start+end)/2),value=current+this._itemHeightSum[middle];if(start>end)return 0;if(value>=0&&value-this._getItemHeight(middle)<0)return middle;isNaN(value)||value>=0?end=middle-1:start=middle+1}},_recalculateItemHeightSum:function(){for(var sums=this._itemHeightSum,i=0,sum=0;i<Math.min(sums.length,this._countItems());i++)sum+=this._getItemHeight(i),sums[i]=sum},_getItemsInView:function(){var topOffset=this._getTopOffset(),topPosition=topOffset,cnt=this._countItems();cnt!==this._itemCount&&(this._recalculateItemHeightSum(),this._maxIndex=cnt-1),this._itemCount=cnt;var startIndex=this._calculateStartIndex(topPosition);startIndex=Math.max(startIndex-30,0),startIndex>0&&(topPosition+=this._itemHeightSum[startIndex-1]);for(var items=[],i=startIndex;cnt>i&&topPosition<4*window.innerHeight;i++){var h=this._getItemHeight(i);i>=this._itemHeightSum.length&&(this._itemHeightSum=this._itemHeightSum.concat(new Array(100))),i>0?this._itemHeightSum[i]=this._itemHeightSum[i-1]+h:this._itemHeightSum[i]=h,this._maxIndex=Math.max(i,this._maxIndex),items.push({index:i,top:topPosition-topOffset}),topPosition+=h}return items},_addSpecialProperties:function(i,scope){scope.$index=i,scope.$first=0===i,scope.$last=i===this._countItems()-1,scope.$middle=!scope.$first&&!scope.$last,scope.$even=i%2===0,scope.$odd=!scope.$even},_onChange:function(){this._render()},_findPageContent:function(){for(var e=this._element[0];e.parentNode;)if(e=e.parentNode,e.className){var classNames=e.className.split(/\s+/);if(classNames.indexOf("page__content")>=0||classNames.indexOf("ons-scroller__content")>=0)return e}return null},_debounce:function(func,wait,immediate){var timeout;return function(){var context=this,args=arguments,later=function(){timeout=null,immediate||func.apply(context,args)},callNow=immediate&&!timeout;clearTimeout(timeout),timeout=setTimeout(later,wait),callNow&&func.apply(context,args)}},_doubleFireOnTouchend:function(){this._render(),this._debounce(this._render.bind(this),100)},_addEventListeners:function(){ons.platform.isIOS()?this._boundOnChange=this._debounce(this._onChange.bind(this),30):this._boundOnChange=this._onChange.bind(this),this._pageContent.addEventListener("scroll",this._boundOnChange,!0),ons.platform.isIOS()&&(this._pageContent.addEventListener("touchmove",this._boundOnChange,!0),this._pageContent.addEventListener("touchend",this._doubleFireOnTouchend,!0)),$document[0].addEventListener("resize",this._boundOnChange,!0)},_removeEventListeners:function(){this._pageContent.removeEventListener("scroll",this._boundOnChange,!0),ons.platform.isIOS()&&(this._pageContent.removeEventListener("touchmove",this._boundOnChange,!0),this._pageContent.removeEventListener("touchend",this._doubleFireOnTouchend,!0)),$document[0].removeEventListener("resize",this._boundOnChange,!0)},_destroy:function(){this._removeEventListeners(),this._removeAllElements(),this._parentElement=this._renderedElements=this._element=this._scope=this._attrs=null}});return LazyRepeatView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("LiftTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){ var LiftTransitionAnimator=NavigatorTransitionAnimator.extend({backgroundMask:angular.element('<div style="position: absolute; width: 100%;height: 100%; background-color: black;"></div>'),push:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();leavePage.element[0].parentNode.insertBefore(mask[0],leavePage.element[0]);var maskClear=animit(mask[0]).wait(.6).queue(function(done){mask.remove(),done()});animit.runAll(maskClear,animit(enterPage.element[0]).queue({css:{transform:"translate3D(0, 100%, 0)"},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).wait(.2).resetStyle().queue(function(done){callback(),done()}),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}))},pop:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();enterPage.element[0].parentNode.insertBefore(mask[0],enterPage.element[0]),animit.runAll(animit(mask[0]).wait(.4).queue(function(done){mask.remove(),done()}),animit(enterPage.element[0]).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().wait(.4).queue(function(done){callback(),done()}),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(0, 100%, 0)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}))}});return LiftTransitionAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("ModalView",["$onsen","$rootScope",function($onsen,$rootScope){var ModalView=Class.extend({_element:void 0,_scope:void 0,init:function(scope,element){this._scope=scope,this._element=element;var pageView=$rootScope.ons.findParentComponentUntil("ons-page",this._element);pageView&&(this._pageContent=angular.element(pageView._element[0].querySelector(".page__content"))),this._scope.$on("$destroy",this._destroy.bind(this)),this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this.hide()},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},show:function(){this._element.css("display","table")},_isVisible:function(){return this._element[0].clientWidth>0},_onDeviceBackButton:function(){},hide:function(){this._element.css("display","none")},toggle:function(){return this._isVisible()?this.hide.apply(this,arguments):this.show.apply(this,arguments)},_destroy:function(){this.emit("destroy",{page:this}),this._deviceBackButtonHandler.destroy(),this._element=this._scope=null}});return MicroEvent.mixin(ModalView),ModalView}])}(),function(){"use strict;";var module=angular.module("onsen"),NavigatorPageObject=Class.extend({init:function(params){this.page=params.page,this.name=params.page,this.element=params.element,this.pageScope=params.pageScope,this.options=params.options,this.navigator=params.navigator,this._blockEvents=function(event){(this.navigator._isPopping||this.navigator._isPushing)&&(event.preventDefault(),event.stopPropagation())}.bind(this),this.element.on(this._pointerEvents,this._blockEvents)},_pointerEvents:"touchmove",getPageView:function(){if(!this._pageView&&(this._pageView=this.element.inheritedData("ons-page"),!this._pageView))throw new Error("Fail to fetch PageView from ons-page element.");return this._pageView},destroy:function(){this.pageScope.$destroy(),this.element.off(this._pointerEvents,this._blockEvents),this.element.remove(),this.element=null,this._pageView=null,this.pageScope=null,this.options=null;var index=this.navigator.pages.indexOf(this);-1!==index&&this.navigator.pages.splice(index,1),this.navigator=null}});module.factory("NavigatorView",["$http","$parse","$templateCache","$compile","$onsen","$timeout","SimpleSlideTransitionAnimator","NavigatorTransitionAnimator","LiftTransitionAnimator","NullTransitionAnimator","IOSSlideTransitionAnimator","FadeTransitionAnimator",function($http,$parse,$templateCache,$compile,$onsen,$timeout,SimpleSlideTransitionAnimator,NavigatorTransitionAnimator,LiftTransitionAnimator,NullTransitionAnimator,IOSSlideTransitionAnimator,FadeTransitionAnimator){var NavigatorView=Class.extend({_element:void 0,_attrs:void 0,pages:void 0,_scope:void 0,_doorLock:void 0,_profiling:!1,init:function(scope,element,attrs){this._element=element||angular.element(window.document.body),this._scope=scope||this._element.scope(),this._attrs=attrs,this._doorLock=new DoorLock,this.pages=[],this._isPopping=this._isPushing=!1,this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this))},_destroy:function(){this.emit("destroy"),this.pages.forEach(function(page){page.destroy()}),this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._element=this._scope=this._attrs=null},_onDeviceBackButton:function(event){this.pages.length>1?this._scope.$evalAsync(this.popPage.bind(this)):event.callParentHandler()},_normalizePageElement:function(element){for(var i=0;i<element.length;i++)if(1===element[i].nodeType)return angular.element(element[i]);throw new Error("invalid state")},_createPageElementAndLinkFunction:function(templateHTML,pageScope,done){function safeApply(scope){var phase=scope.$root.$$phase;"$apply"!==phase&&"$digest"!==phase&&scope.$apply()}var div=document.createElement("div");div.innerHTML=templateHTML.trim();var pageElement=angular.element(div),hasPage=1===div.childElementCount&&"ons-page"===div.childNodes[0].nodeName.toLowerCase();if(!hasPage)throw new Error('You can not supply no "ons-page" element to "ons-navigator".');pageElement=angular.element(div.childNodes[0]);var link=$compile(pageElement);return{element:pageElement,link:function(){link(pageScope),safeApply(pageScope)}}},insertPage:function(index,page,options){if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);if(index===this.pages.length)return this.pushPage.apply(this,[].slice.call(arguments,1));this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock();$onsen.getPageHTMLAsync(page).then(function(templateHTML){var pageScope=this._createPageScope(),object=this._createPageElementAndLinkFunction(templateHTML,pageScope),element=object.element,link=object.link;element=this._normalizePageElement(element);var pageObject=this._createPageObject(page,element,pageScope,options);this.pages.length>0?(index=normalizeIndex(index),this._element[0].insertBefore(element[0],this.pages[index]?this.pages[index].element[0]:null),this.pages.splice(index,0,pageObject),link(),setTimeout(function(){this.getCurrentPage()!==pageObject&&element.css("display","none"),unlock(),element=null}.bind(this),1e3/60)):(this._element.append(element),this.pages.push(pageObject),link(),unlock(),element=null)}.bind(this),function(){throw unlock(),new Error("Page is not found: "+page)})}.bind(this));var normalizeIndex=function(index){return 0>index&&(index=this.pages.length+index),index}.bind(this)},pushPage:function(page,options){if(this._profiling&&console.time("pushPage"),options=options||{},!options.cancelIfRunning||!this._isPushing){if(options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);this._emitPrePushEvent()||this._doorLock.waitUnlock(function(){this._pushPage(page,options)}.bind(this))}},_pushPage:function(page,options){var unlock=this._doorLock.lock(),done=function(){unlock(),this._profiling&&console.timeEnd("pushPage")};$onsen.getPageHTMLAsync(page).then(function(templateHTML){var pageScope=this._createPageScope(),object=this._createPageElementAndLinkFunction(templateHTML,pageScope);setImmediate(function(){this._pushPageDOM(page,object.element,object.link,pageScope,options,done),object=null}.bind(this))}.bind(this),function(){throw done(),new Error("Page is not found: "+page)}.bind(this))},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},_getAnimatorOption:function(options,defaultAnimator){var animator=null;if(options.animation instanceof NavigatorTransitionAnimator)return options.animation;if("string"==typeof options.animation&&(animator=NavigatorView._transitionAnimatorDict[options.animation]),!animator&&this._element.attr("animation")&&(animator=NavigatorView._transitionAnimatorDict[this._element.attr("animation")]),animator||(animator=defaultAnimator||NavigatorView._transitionAnimatorDict["default"]),!(animator instanceof NavigatorTransitionAnimator))throw new Error('"animator" is not an instance of NavigatorTransitionAnimator.');return animator},_createPageScope:function(){return this._scope.$new()},_createPageObject:function(page,element,pageScope,options){return options.animator=this._getAnimatorOption(options),new NavigatorPageObject({page:page,element:element,pageScope:pageScope,options:options,navigator:this})},_pushPageDOM:function(page,element,link,pageScope,options,unlock){this._profiling&&console.time("pushPageDOM"),unlock=unlock||function(){},options=options||{},element=this._normalizePageElement(element);var pageObject=this._createPageObject(page,element,pageScope,options),event={enterPage:pageObject,leavePage:this.pages[this.pages.length-1],navigator:this};this.pages.push(pageObject);var done=function(){this.pages[this.pages.length-2]&&this.pages[this.pages.length-2].element.css("display","none"),this._profiling&&console.timeEnd("pushPageDOM"),this._isPushing=!1,unlock(),this.emit("postpush",event),"function"==typeof options.onTransitionEnd&&options.onTransitionEnd(),element=null}.bind(this);if(this._isPushing=!0,this.pages.length>1){var leavePage=this.pages.slice(-2)[0],enterPage=this.pages.slice(-1)[0];this._element.append(element),link(),options.animator.push(enterPage,leavePage,done),element=null}else this._element.append(element),link(),done(),element=null},_emitPrePushEvent:function(){var isCanceled=!1,prePushEvent={navigator:this,currentPage:this.getCurrentPage(),cancel:function(){isCanceled=!0}};return this.emit("prepush",prePushEvent),isCanceled},_emitPrePopEvent:function(){var isCanceled=!1,leavePage=this.getCurrentPage(),prePopEvent={navigator:this,currentPage:leavePage,leavePage:leavePage,enterPage:this.pages[this.pages.length-2],cancel:function(){isCanceled=!0}};return this.emit("prepop",prePopEvent),isCanceled},popPage:function(options){options=options||{},options.cancelIfRunning&&this._isPopping||this._doorLock.waitUnlock(function(){if(this.pages.length<=1)throw new Error("NavigatorView's page stack is empty.");this._emitPrePopEvent()||this._popPage(options)}.bind(this))},_popPage:function(options){var unlock=this._doorLock.lock(),leavePage=this.pages.pop();this.pages[this.pages.length-1]&&this.pages[this.pages.length-1].element.css("display","block");var enterPage=this.pages[this.pages.length-1],event={leavePage:leavePage,enterPage:this.pages[this.pages.length-1],navigator:this},callback=function(){leavePage.destroy(),this._isPopping=!1,unlock(),this.emit("postpop",event),event.leavePage=null,"function"==typeof options.onTransitionEnd&&options.onTransitionEnd()}.bind(this);this._isPopping=!0;var animator=this._getAnimatorOption(options,leavePage.options.animator);animator.pop(enterPage,leavePage,callback)},replacePage:function(page,options){options=options||{};var onTransitionEnd=options.onTransitionEnd||function(){};options.onTransitionEnd=function(){this.pages.length>1&&this.pages[this.pages.length-2].destroy(),onTransitionEnd()}.bind(this),this.pushPage(page,options)},resetToPage:function(page,options){options=options||{},options.animator||options.animation||(options.animation="none");var onTransitionEnd=options.onTransitionEnd||function(){},self=this;options.onTransitionEnd=function(){for(;self.pages.length>1;)self.pages.shift().destroy();self._scope.$digest(),onTransitionEnd()},this.pushPage(page,options)},getCurrentPage:function(){return this.pages[this.pages.length-1]},getPages:function(){return this.pages},canPopPage:function(){return this.pages.length>1}});return NavigatorView._transitionAnimatorDict={"default":$onsen.isAndroid()?new SimpleSlideTransitionAnimator:new IOSSlideTransitionAnimator,slide:$onsen.isAndroid()?new SimpleSlideTransitionAnimator:new IOSSlideTransitionAnimator,simpleslide:new SimpleSlideTransitionAnimator,lift:new LiftTransitionAnimator,fade:new FadeTransitionAnimator,none:new NullTransitionAnimator},NavigatorView.registerTransitionAnimator=function(name,animator){if(!(animator instanceof NavigatorTransitionAnimator))throw new Error('"animator" param must be an instance of NavigatorTransitionAnimator');this._transitionAnimatorDict[name]=animator},MicroEvent.mixin(NavigatorView),NavigatorView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("NavigatorTransitionAnimator",function(){var NavigatorTransitionAnimator=Class.extend({push:function(enterPage,leavePage,callback){callback()},pop:function(enterPage,leavePage,callback){callback()}});return NavigatorTransitionAnimator})}(),function(){"use strict;";var module=angular.module("onsen");module.factory("NullTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var NullTransitionAnimator=NavigatorTransitionAnimator.extend({});return NullTransitionAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("OverlaySlidingMenuAnimator",["SlidingMenuAnimator",function(SlidingMenuAnimator){var OverlaySlidingMenuAnimator=SlidingMenuAnimator.extend({_blackMask:void 0,_isRight:!1,_element:!1,_menuPage:!1,_mainPage:!1,_width:!1,_duration:!1,setup:function(element,mainPage,menuPage,options){options=options||{},this._width=options.width||"90%",this._isRight=!!options.isRight,this._element=element,this._mainPage=mainPage,this._menuPage=menuPage,this._duration=.4,menuPage.css("box-shadow","0px 0 10px 0px rgba(0, 0, 0, 0.2)"),menuPage.css({width:options.width,display:"none",zIndex:2}),menuPage.css("-webkit-transform","translate3d(0px, 0px, 0px)"),mainPage.css({zIndex:1}),this._isRight?menuPage.css({right:"-"+options.width,left:"auto"}):menuPage.css({right:"auto",left:"-"+options.width}),this._blackMask=angular.element("<div></div>").css({backgroundColor:"black",top:"0px",left:"0px",right:"0px",bottom:"0px",position:"absolute",display:"none",zIndex:0}),element.prepend(this._blackMask)},onResized:function(options){if(this._menuPage.css("width",options.width),this._isRight?this._menuPage.css({right:"-"+options.width,left:"auto"}):this._menuPage.css({right:"auto",left:"-"+options.width}),options.isOpened){var max=this._menuPage[0].clientWidth,menuStyle=this._generateMenuPageStyle(max);animit(this._menuPage[0]).queue(menuStyle).play()}},destroy:function(){this._blackMask&&(this._blackMask.remove(),this._blackMask=null),this._mainPage.removeAttr("style"),this._menuPage.removeAttr("style"),this._element=this._mainPage=this._menuPage=null},openMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._menuPage.css("display","block"),this._blackMask.css("display","block");var max=this._menuPage[0].clientWidth,menuStyle=this._generateMenuPageStyle(max),mainPageStyle=this._generateMainPageStyle(max);setTimeout(function(){animit(this._mainPage[0]).queue(mainPageStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){callback(),done()}).play(),animit(this._menuPage[0]).queue(menuStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},closeMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._blackMask.css({display:"block"});var menuPageStyle=this._generateMenuPageStyle(0),mainPageStyle=this._generateMainPageStyle(0);setTimeout(function(){animit(this._mainPage[0]).queue(mainPageStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){this._menuPage.css("display","none"),callback(),done()}.bind(this)).play(),animit(this._menuPage[0]).queue(menuPageStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},translateMenu:function(options){this._menuPage.css("display","block"),this._blackMask.css({display:"block"});var menuPageStyle=this._generateMenuPageStyle(Math.min(options.maxDistance,options.distance)),mainPageStyle=this._generateMainPageStyle(Math.min(options.maxDistance,options.distance));delete mainPageStyle.opacity,animit(this._menuPage[0]).queue(menuPageStyle).play(),Object.keys(mainPageStyle).length>0&&animit(this._mainPage[0]).queue(mainPageStyle).play()},_generateMenuPageStyle:function(distance){var x=(this._menuPage[0].clientWidth,this._isRight?-distance:distance),transform="translate3d("+x+"px, 0, 0)";return{transform:transform,"box-shadow":0===distance?"none":"0px 0 10px 0px rgba(0, 0, 0, 0.2)"}},_generateMainPageStyle:function(distance){var max=this._menuPage[0].clientWidth,opacity=1-.1*distance/max;return{opacity:opacity}},copy:function(){return new OverlaySlidingMenuAnimator}});return OverlaySlidingMenuAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("PageView",["$onsen","$parse",function($onsen,$parse){var PageView=Class.extend({_registeredToolbarElement:!1,_registeredBottomToolbarElement:!1,_nullElement:window.document.createElement("div"),_toolbarElement:null,_bottomToolbarElement:null,init:function(scope,element,attrs){this._scope=scope,this._element=element,this._attrs=attrs,this._registeredToolbarElement=!1,this._registeredBottomToolbarElement=!1,this._nullElement=window.document.createElement("div"),this._toolbarElement=angular.element(this._nullElement),this._bottomToolbarElement=angular.element(this._nullElement),this._clearListener=scope.$on("$destroy",this._destroy.bind(this)),this._userDeviceBackButtonListener=angular.noop,(this._attrs.ngDeviceBackbutton||this._attrs.onDeviceBackbutton)&&(this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)))},_onDeviceBackButton:function($event){if(this._userDeviceBackButtonListener($event),this._attrs.ngDeviceBackbutton&&$parse(this._attrs.ngDeviceBackbutton)(this._scope,{$event:$event}),this._attrs.onDeviceBackbutton){var lastEvent=window.$event;window.$event=$event,new Function(this._attrs.onDeviceBackbutton)(),window.$event=lastEvent}},setDeviceBackButtonHandler:function(callback){this._deviceBackButtonHandler||(this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this))),this._userDeviceBackButtonListener=callback},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler||null},registerToolbar:function(element){if(this._registeredToolbarElement)throw new Error("This page's toolbar is already registered.");angular.element(this.getContentElement()).attr("no-status-bar-fill",""),element.remove();var statusFill=this._element[0].querySelector(".page__status-bar-fill");statusFill?angular.element(statusFill).after(element):this._element.prepend(element),this._toolbarElement=element,this._registeredToolbarElement=!0},registerBottomToolbar:function(element){if(this._registeredBottomToolbarElement)throw new Error("This page's bottom-toolbar is already registered.");element.remove(),this._bottomToolbarElement=element,this._registeredBottomToolbarElement=!0;var fill=angular.element(document.createElement("div"));fill.addClass("page__bottom-bar-fill"),fill.css({width:"0px",height:"0px"}),this._element.prepend(fill),this._element.append(element)},registerExtraElement:function(element){this._extraElement||(this._extraElement=angular.element("<div></div>"),this._extraElement.addClass("page__extra"),this._extraElement.css({"z-index":"10001"}),this._element.append(this._extraElement)),this._extraElement.append(element.remove())},hasToolbarElement:function(){return!!this._registeredToolbarElement},hasBottomToolbarElement:function(){return!!this._registeredBottomToolbarElement},getContentElement:function(){for(var i=0;i<this._element.length;i++)if(this._element[i].querySelector){var content=this._element[i].querySelector(".page__content");if(content)return content}throw Error('fail to get ".page__content" element.')},getBackgroundElement:function(){for(var i=0;i<this._element.length;i++)if(this._element[i].querySelector){var content=this._element[i].querySelector(".page__background");if(content)return content}throw Error('fail to get ".page__background" element.')},getToolbarElement:function(){return this._toolbarElement[0]||this._nullElement},getBottomToolbarElement:function(){return this._bottomToolbarElement[0]||this._nullElement},getToolbarLeftItemsElement:function(){return this._toolbarElement[0].querySelector(".left")||this._nullElement},getToolbarCenterItemsElement:function(){return this._toolbarElement[0].querySelector(".center")||this._nullElement},getToolbarRightItemsElement:function(){return this._toolbarElement[0].querySelector(".right")||this._nullElement},getToolbarBackButtonLabelElement:function(){return this._toolbarElement[0].querySelector("ons-back-button .back-button__label")||this._nullElement},_destroy:function(){this.emit("destroy",{page:this}),this._deviceBackButtonHandler&&(this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null),this._element=null,this._toolbarElement=null,this._nullElement=null,this._bottomToolbarElement=null,this._extraElement=null,this._scope=null,this._clearListener()}});return MicroEvent.mixin(PageView),PageView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("PopoverView",["$onsen","PopoverAnimator","FadePopoverAnimator",function($onsen,PopoverAnimator,FadePopoverAnimator){var PopoverView=Class.extend({init:function(scope,element,attrs){if(this._element=element,this._scope=scope,this._attrs=attrs,this._mask=angular.element(this._element[0].querySelector(".popover-mask")),this._popover=angular.element(this._element[0].querySelector(".popover")),this._mask.css("z-index",2e4),this._popover.css("z-index",20001),this._element.css("display","none"),attrs.maskColor&&this._mask.css("background-color",attrs.maskColor),this._mask.on("click",this._cancel.bind(this)),this._visible=!1,this._doorLock=new DoorLock,this._animation=PopoverView._animatorDict["undefined"!=typeof attrs.animation?attrs.animation:"fade"],!this._animation)throw new Error("No such animation: "+attrs.animation);this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._onChange=function(){setImmediate(function(){this._currentTarget&&this._positionPopover(this._currentTarget)}.bind(this))}.bind(this),this._popover[0].addEventListener("DOMNodeInserted",this._onChange,!1),this._popover[0].addEventListener("DOMNodeRemoved",this._onChange,!1),window.addEventListener("resize",this._onChange,!1),this._scope.$on("$destroy",this._destroy.bind(this))},_onDeviceBackButton:function(event){this.isCancelable()?this._cancel.bind(this)():event.callParentHandler()},_setDirection:function(direction){if("up"===direction)this._scope.direction=direction,this._scope.arrowPosition="bottom";else if("left"===direction)this._scope.direction=direction,this._scope.arrowPosition="right";else if("down"===direction)this._scope.direction=direction,this._scope.arrowPosition="top";else{if("right"!=direction)throw new Error("Invalid direction.");this._scope.direction=direction,this._scope.arrowPosition="left"}this._scope.$$phase||this._scope.$apply()},_positionPopoverByDirection:function(target,direction){var el=angular.element(this._element[0].querySelector(".popover")),pos=target.getBoundingClientRect(),own=el[0].getBoundingClientRect(),arrow=angular.element(el.children()[1]),offset=14,margin=6,radius=parseInt(window.getComputedStyle(el[0].querySelector(".popover__content")).borderRadius);arrow.css({top:"",left:""});var diff=function(x){return x/2*Math.sqrt(2)-x/2}(parseInt(window.getComputedStyle(arrow[0]).width)),limit=margin+radius+diff;this._setDirection(direction),["left","right"].indexOf(direction)>-1?("left"==direction?el.css("left",pos.right-pos.width-own.width-offset+"px"):el.css("left",pos.right+offset+"px"),el.css("top",pos.bottom-pos.height/2-own.height/2+"px")):("up"==direction?el.css("top",pos.bottom-pos.height-own.height-offset+"px"):el.css("top",pos.bottom+offset+"px"),el.css("left",pos.right-pos.width/2-own.width/2+"px")),own=el[0].getBoundingClientRect(),["left","right"].indexOf(direction)>-1?own.top<margin?(arrow.css("top",Math.max(own.height/2+own.top-margin,limit)+"px"),el.css("top",margin+"px")):own.bottom>window.innerHeight-margin&&(arrow.css("top",Math.min(own.height/2-(window.innerHeight-own.bottom)+margin,own.height-limit)+"px"),el.css("top",window.innerHeight-own.height-margin+"px")):own.left<margin?(arrow.css("left",Math.max(own.width/2+own.left-margin,limit)+"px"),el.css("left",margin+"px")):own.right>window.innerWidth-margin&&(arrow.css("left",Math.min(own.width/2-(window.innerWidth-own.right)+margin,own.width-limit)+"px"),el.css("left",window.innerWidth-own.width-margin+"px"))},_positionPopover:function(target){var directions;directions=this._element.attr("direction")?this._element.attr("direction").split(/\s+/):["up","down","left","right"];for(var position=target.getBoundingClientRect(),scores={left:position.left,right:window.innerWidth-position.right,up:position.top,down:window.innerHeight-position.bottom},orderedDirections=Object.keys(scores).sort(function(a,b){return-(scores[a]-scores[b])}),i=0,l=orderedDirections.length;l>i;i++){var direction=orderedDirections[i];if(directions.indexOf(direction)>-1)return void this._positionPopoverByDirection(target,direction)}},show:function(target,options){if("string"==typeof target?target=document.querySelector(target):target instanceof Event&&(target=target.target),!target)throw new Error("Target undefined");options=options||{};var cancel=!1;this.emit("preshow",{popover:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;this._element.css("display","block"),this._currentTarget=target,this._positionPopover(target),options.animation&&(animation=PopoverView._animatorDict[options.animation]),animation.show(this,function(){this._visible=!0,this._positionPopover(target),unlock(),this.emit("postshow",{popover:this})}.bind(this))}.bind(this))},hide:function(options){options=options||{};var cancel=!1;this.emit("prehide",{popover:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;options.animation&&(animation=PopoverView._animatorDict[options.animation]),animation.hide(this,function(){this._element.css("display","none"),this._visible=!1,unlock(),this.emit("posthide",{popover:this})}.bind(this))}.bind(this))},isShown:function(){return this._visible},destroy:function(){this._parentScope?(this._parentScope.$destroy(),this._parentScope=null):this._scope.$destroy()},_destroy:function(){this.emit("destroy"),this._deviceBackButtonHandler.destroy(),this._popover[0].removeEventListener("DOMNodeInserted",this._onChange,!1),this._popover[0].removeEventListener("DOMNodeRemoved",this._onChange,!1),window.removeEventListener("resize",this._onChange,!1),this._mask.off(),this._mask.remove(),this._popover.remove(),this._element.remove(),this._onChange=this._deviceBackButtonHandler=this._mask=this._popover=this._element=this._scope=null},setCancelable:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this._element.attr("cancelable",!0):this._element.removeAttr("cancelable")},isCancelable:function(){return this._element[0].hasAttribute("cancelable")},_cancel:function(){this.isCancelable()&&this.hide()}});return PopoverView._animatorDict={fade:new FadePopoverAnimator,none:new PopoverAnimator},PopoverView.registerAnimator=function(name,animator){if(!(animator instanceof PopoverAnimator))throw new Error('"animator" param must be an instance of PopoverAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(PopoverView),PopoverView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("PopoverAnimator",function(){var PopoverAnimator=Class.extend({show:function(popover,callback){callback()},hide:function(popover,callback){callback()}});return PopoverAnimator})}(),function(){"use strict";var module=angular.module("onsen");module.factory("PullHookView",["$onsen","$parse",function($onsen,$parse){var PullHookView=Class.extend({STATE_INITIAL:"initial",STATE_PREACTION:"preaction",STATE_ACTION:"action",init:function(scope,element,attrs){if(this._element=element,this._scope=scope,this._attrs=attrs,this._scrollElement=this._createScrollElement(),this._pageElement=this._scrollElement.parent(),!this._pageElement.hasClass("page__content")&&!this._pageElement.hasClass("ons-scroller__content"))throw new Error("<ons-pull-hook> must be a direct descendant of an <ons-page> or an <ons-scroller> element.");this._currentTranslation=0,this._createEventListeners(),this._setState(this.STATE_INITIAL,!0),this._setStyle(),this._scope.$on("$destroy",this._destroy.bind(this))},_createScrollElement:function(){var scrollElement=angular.element("<div>").addClass("scroll"),pageElement=this._element.parent(),children=pageElement.children();return pageElement.append(scrollElement),scrollElement.append(children),scrollElement},_setStyle:function(){var h=this._getHeight();this._element.css({top:"-"+h+"px",height:h+"px",lineHeight:h+"px"})},_onScroll:function(event){var el=this._pageElement[0];el.scrollTop<0&&(el.scrollTop=0)},_generateTranslationTransform:function(scroll){return"translate3d(0px, "+scroll+"px, 0px)"},_onDrag:function(event){if(!this.isDisabled()&&"left"!==event.gesture.direction&&"right"!==event.gesture.direction){var el=this._pageElement[0];if(el.scrollTop=this._startScroll-event.gesture.deltaY,el.scrollTop<window.innerHeight&&"up"!==event.gesture.direction&&event.gesture.preventDefault(),0===this._currentTranslation&&0===this._getCurrentScroll()){this._transitionDragLength=event.gesture.deltaY;var direction=event.gesture.interimDirection;"down"===direction?this._transitionDragLength-=1:this._transitionDragLength+=1}var scroll=event.gesture.deltaY-this._startScroll;scroll=Math.max(scroll,0),this._thresholdHeightEnabled()&&scroll>=this._getThresholdHeight()?(event.gesture.stopDetect(),setImmediate(function(){this._setState(this.STATE_ACTION),this._translateTo(this._getHeight(),{animate:!0}),this._waitForAction(this._onDone.bind(this))}.bind(this))):scroll>=this._getHeight()?this._setState(this.STATE_PREACTION):this._setState(this.STATE_INITIAL),event.stopPropagation(),this._translateTo(scroll)}},_onDragStart:function(event){this.isDisabled()||(this._startScroll=this._getCurrentScroll())},_onDragEnd:function(event){if(!this.isDisabled()&&this._currentTranslation>0){var scroll=this._currentTranslation;scroll>this._getHeight()?(this._setState(this.STATE_ACTION),this._translateTo(this._getHeight(),{animate:!0}),this._waitForAction(this._onDone.bind(this))):this._translateTo(0,{animate:!0})}},_waitForAction:function(done){this._attrs.ngAction?this._scope.$eval(this._attrs.ngAction,{$done:done}):this._attrs.onAction?eval(this._attrs.onAction):done()},_onDone:function(done){this._element&&(this._translateTo(0,{animate:!0}),this._setState(this.STATE_INITIAL))},_getHeight:function(){return parseInt(this._element[0].getAttribute("height")||"64",10)},setHeight:function(height){this._element[0].setAttribute("height",height+"px"),this._setStyle()},setThresholdHeight:function(thresholdHeight){this._element[0].setAttribute("threshold-height",thresholdHeight+"px")},_getThresholdHeight:function(){return parseInt(this._element[0].getAttribute("threshold-height")||"96",10); },_thresholdHeightEnabled:function(){var th=this._getThresholdHeight();return th>0&&th>=this._getHeight()},_setState:function(state,noEvent){var oldState=this._getState();this._scope.$evalAsync(function(){this._element[0].setAttribute("state",state),noEvent||oldState===this._getState()||this.emit("changestate",{state:state,pullHook:this})}.bind(this))},_getState:function(){return this._element[0].getAttribute("state")},getCurrentState:function(){return this._getState()},_getCurrentScroll:function(){return this._pageElement[0].scrollTop},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setDisabled:function(disabled){disabled?this._element[0].setAttribute("disabled",""):this._element[0].removeAttribute("disabled")},_translateTo:function(scroll,options){if(options=options||{},0!=this._currentTranslation||0!=scroll){var done=function(){0===scroll&&this._scrollElement[0].removeAttribute("style"),options.callback&&options.callback()}.bind(this);this._currentTranslation=scroll,options.animate?animit(this._scrollElement[0]).queue({transform:this._generateTranslationTransform(scroll)},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(done):animit(this._scrollElement[0]).queue({transform:this._generateTranslationTransform(scroll)}).play(done)}},_getMinimumScroll:function(){var scrollHeight=this._scrollElement[0].getBoundingClientRect().height,pageHeight=this._pageElement[0].getBoundingClientRect().height;return scrollHeight>pageHeight?-(scrollHeight-pageHeight):0},_createEventListeners:function(){var element=this._scrollElement.parent();this._hammer=new Hammer(element[0],{dragMinDistance:1,dragDistanceCorrection:!1}),this._bindedOnDrag=this._onDrag.bind(this),this._bindedOnDragStart=this._onDragStart.bind(this),this._bindedOnDragEnd=this._onDragEnd.bind(this),this._bindedOnScroll=this._onScroll.bind(this),this._hammer.on("drag",this._bindedOnDrag),this._hammer.on("dragstart",this._bindedOnDragStart),this._hammer.on("dragend",this._bindedOnDragEnd),element.on("scroll",this._bindedOnScroll)},_destroyEventListeners:function(){var element=this._scrollElement.parent();this._hammer.off("drag",this._bindedOnDrag),this._hammer.off("dragstart",this._bindedOnDragStart),this._hammer.off("dragend",this._bindedOnDragEnd),element.off("scroll",this._bindedOnScroll)},_destroy:function(){this.emit("destroy"),this._destroyEventListeners(),this._element=this._scope=this._attrs=null}});return MicroEvent.mixin(PullHookView),PullHookView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("PushSlidingMenuAnimator",["SlidingMenuAnimator",function(SlidingMenuAnimator){var PushSlidingMenuAnimator=SlidingMenuAnimator.extend({_isRight:!1,_element:void 0,_menuPage:void 0,_mainPage:void 0,_width:void 0,_duration:!1,setup:function(element,mainPage,menuPage,options){options=options||{},this._element=element,this._mainPage=mainPage,this._menuPage=menuPage,this._isRight=!!options.isRight,this._width=options.width||"90%",this._duration=.4,menuPage.css({width:options.width,display:"none"}),this._isRight?menuPage.css({right:"-"+options.width,left:"auto"}):menuPage.css({right:"auto",left:"-"+options.width})},onResized:function(options){if(this._menuPage.css("width",options.width),this._isRight?this._menuPage.css({right:"-"+options.width,left:"auto"}):this._menuPage.css({right:"auto",left:"-"+options.width}),options.isOpened){var max=this._menuPage[0].clientWidth,mainPageTransform=this._generateAbovePageTransform(max),menuPageStyle=this._generateBehindPageStyle(max);animit(this._mainPage[0]).queue({transform:mainPageTransform}).play(),animit(this._menuPage[0]).queue(menuPageStyle).play()}},destroy:function(){this._mainPage.removeAttr("style"),this._menuPage.removeAttr("style"),this._element=this._mainPage=this._menuPage=null},openMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._menuPage.css("display","block");var max=this._menuPage[0].clientWidth,aboveTransform=this._generateAbovePageTransform(max),behindStyle=this._generateBehindPageStyle(max);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){callback(),done()}).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},closeMenu:function(callback,instant){var duration=instant===!0?0:this._duration,aboveTransform=this._generateAbovePageTransform(0),behindStyle=this._generateBehindPageStyle(0);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue({transform:"translate3d(0, 0, 0)"}).queue(function(done){this._menuPage.css("display","none"),callback(),done()}.bind(this)).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done()}).play()}.bind(this),1e3/60)},translateMenu:function(options){this._menuPage.css("display","block");var aboveTransform=this._generateAbovePageTransform(Math.min(options.maxDistance,options.distance)),behindStyle=this._generateBehindPageStyle(Math.min(options.maxDistance,options.distance));animit(this._mainPage[0]).queue({transform:aboveTransform}).play(),animit(this._menuPage[0]).queue(behindStyle).play()},_generateAbovePageTransform:function(distance){var x=this._isRight?-distance:distance,aboveTransform="translate3d("+x+"px, 0, 0)";return aboveTransform},_generateBehindPageStyle:function(distance){var behindX=(this._menuPage[0].clientWidth,this._isRight?-distance:distance),behindTransform="translate3d("+behindX+"px, 0, 0)";return{transform:behindTransform}},copy:function(){return new PushSlidingMenuAnimator}});return PushSlidingMenuAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("RevealSlidingMenuAnimator",["SlidingMenuAnimator",function(SlidingMenuAnimator){var RevealSlidingMenuAnimator=SlidingMenuAnimator.extend({_blackMask:void 0,_isRight:!1,_menuPage:void 0,_element:void 0,_mainPage:void 0,_duration:void 0,setup:function(element,mainPage,menuPage,options){this._element=element,this._menuPage=menuPage,this._mainPage=mainPage,this._isRight=!!options.isRight,this._width=options.width||"90%",this._duration=.4,mainPage.css({boxShadow:"0px 0 10px 0px rgba(0, 0, 0, 0.2)"}),menuPage.css({width:options.width,opacity:.9,display:"none"}),this._isRight?menuPage.css({right:"0px",left:"auto"}):menuPage.css({right:"auto",left:"0px"}),this._blackMask=angular.element("<div></div>").css({backgroundColor:"black",top:"0px",left:"0px",right:"0px",bottom:"0px",position:"absolute",display:"none"}),element.prepend(this._blackMask),animit(mainPage[0]).queue({transform:"translate3d(0, 0, 0)"}).play()},onResized:function(options){if(this._width=options.width,this._menuPage.css("width",this._width),options.isOpened){var max=this._menuPage[0].clientWidth,aboveTransform=this._generateAbovePageTransform(max),behindStyle=this._generateBehindPageStyle(max);animit(this._mainPage[0]).queue({transform:aboveTransform}).play(),animit(this._menuPage[0]).queue(behindStyle).play()}},destroy:function(){this._blackMask&&(this._blackMask.remove(),this._blackMask=null),this._mainPage&&this._mainPage.attr("style",""),this._menuPage&&this._menuPage.attr("style",""),this._mainPage=this._menuPage=this._element=void 0},openMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._menuPage.css("display","block"),this._blackMask.css("display","block");var max=this._menuPage[0].clientWidth,aboveTransform=this._generateAbovePageTransform(max),behindStyle=this._generateBehindPageStyle(max);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){callback(),done()}).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},closeMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._blackMask.css("display","block");var aboveTransform=this._generateAbovePageTransform(0),behindStyle=this._generateBehindPageStyle(0);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue({transform:"translate3d(0, 0, 0)"}).queue(function(done){this._menuPage.css("display","none"),callback(),done()}.bind(this)).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done()}).play()}.bind(this),1e3/60)},translateMenu:function(options){this._menuPage.css("display","block"),this._blackMask.css("display","block");var aboveTransform=this._generateAbovePageTransform(Math.min(options.maxDistance,options.distance)),behindStyle=this._generateBehindPageStyle(Math.min(options.maxDistance,options.distance));delete behindStyle.opacity,animit(this._mainPage[0]).queue({transform:aboveTransform}).play(),animit(this._menuPage[0]).queue(behindStyle).play()},_generateAbovePageTransform:function(distance){var x=this._isRight?-distance:distance,aboveTransform="translate3d("+x+"px, 0, 0)";return aboveTransform},_generateBehindPageStyle:function(distance){var max=this._menuPage[0].getBoundingClientRect().width,behindDistance=(distance-max)/max*10;behindDistance=isNaN(behindDistance)?0:Math.max(Math.min(behindDistance,0),-10);var behindX=this._isRight?-behindDistance:behindDistance,behindTransform="translate3d("+behindX+"%, 0, 0)",opacity=1+behindDistance/100;return{transform:behindTransform,opacity:opacity}},copy:function(){return new RevealSlidingMenuAnimator}});return RevealSlidingMenuAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("SimpleSlideTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var SimpleSlideTransitionAnimator=NavigatorTransitionAnimator.extend({backgroundMask:angular.element('<div style="z-index: 2; position: absolute; width: 100%;height: 100%; background-color: black; opacity: 0;"></div>'),timing:"cubic-bezier(.1, .7, .4, 1)",duration:.3,blackMaskOpacity:.4,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},push:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();leavePage.element[0].parentNode.insertBefore(mask[0],leavePage.element[0].nextSibling),animit.runAll(animit(mask[0]).queue({opacity:0,transform:"translate3d(0, 0, 0)"}).queue({opacity:this.blackMaskOpacity},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){mask.remove(),done()}),animit(enterPage.element[0]).queue({css:{transform:"translate3D(100%, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(-45%, 0px, 0px)"},duration:this.duration,timing:this.timing}).resetStyle().wait(.2).queue(function(done){callback(),done()}))},pop:function(enterPage,leavePage,done){var mask=this.backgroundMask.remove();enterPage.element[0].parentNode.insertBefore(mask[0],enterPage.element[0].nextSibling),animit.runAll(animit(mask[0]).queue({opacity:this.blackMaskOpacity,transform:"translate3d(0, 0, 0)"}).queue({opacity:0},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){mask.remove(),done()}),animit(enterPage.element[0]).queue({css:{transform:"translate3D(-45%, 0px, 0px)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(.2).queue(function(finish){done(),finish()}))}});return SimpleSlideTransitionAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("SlideDialogAnimator",["DialogAnimator",function(DialogAnimator){var SlideDialogAnimator=DialogAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:0}).queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:0}).queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return SlideDialogAnimator}])}(),function(){"use strict";var module=angular.module("onsen"),SlidingMenuViewModel=Class.extend({_distance:0,_maxDistance:void 0,init:function(options){if(!angular.isNumber(options.maxDistance))throw new Error("options.maxDistance must be number");this.setMaxDistance(options.maxDistance)},setMaxDistance:function(maxDistance){if(0>=maxDistance)throw new Error("maxDistance must be greater then zero.");this.isOpened()&&(this._distance=maxDistance),this._maxDistance=maxDistance},shouldOpen:function(){return!this.isOpened()&&this._distance>=this._maxDistance/2},shouldClose:function(){return!this.isClosed()&&this._distance<this._maxDistance/2},openOrClose:function(options){this.shouldOpen()?this.open(options):this.shouldClose()&&this.close(options)},close:function(options){var callback=options.callback||function(){};this.isClosed()?callback():(this._distance=0,this.emit("close",options))},open:function(options){var callback=options.callback||function(){};this.isOpened()?callback():(this._distance=this._maxDistance,this.emit("open",options))},isClosed:function(){return 0===this._distance},isOpened:function(){return this._distance===this._maxDistance},getX:function(){return this._distance},getMaxDistance:function(){return this._maxDistance},translate:function(x){this._distance=Math.max(1,Math.min(this._maxDistance-1,x));var options={distance:this._distance,maxDistance:this._maxDistance};this.emit("translate",options)},toggle:function(){this.isClosed()?this.open():this.close()}});MicroEvent.mixin(SlidingMenuViewModel),module.factory("SlidingMenuView",["$onsen","$compile","SlidingMenuAnimator","RevealSlidingMenuAnimator","PushSlidingMenuAnimator","OverlaySlidingMenuAnimator",function($onsen,$compile,SlidingMenuAnimator,RevealSlidingMenuAnimator,PushSlidingMenuAnimator,OverlaySlidingMenuAnimator){var SlidingMenuView=Class.extend({_scope:void 0,_attrs:void 0,_element:void 0,_menuPage:void 0,_mainPage:void 0,_doorLock:void 0,_isRightMenu:!1,init:function(scope,element,attrs){this._scope=scope,this._attrs=attrs,this._element=element,this._menuPage=angular.element(element[0].querySelector(".onsen-sliding-menu__menu")),this._mainPage=angular.element(element[0].querySelector(".onsen-sliding-menu__main")),this._doorLock=new DoorLock,this._isRightMenu="right"===attrs.side,this._mainPageHammer=new Hammer(this._mainPage[0]),this._bindedOnTap=this._onTap.bind(this);var maxDistance=this._normalizeMaxSlideDistanceAttr();this._logic=new SlidingMenuViewModel({maxDistance:Math.max(maxDistance,1)}),this._logic.on("translate",this._translate.bind(this)),this._logic.on("open",function(options){this._open(options)}.bind(this)),this._logic.on("close",function(options){this._close(options)}.bind(this)),attrs.$observe("maxSlideDistance",this._onMaxSlideDistanceChanged.bind(this)),attrs.$observe("swipeable",this._onSwipeableChanged.bind(this)),this._bindedOnWindowResize=this._onWindowResize.bind(this),window.addEventListener("resize",this._bindedOnWindowResize),this._boundHandleEvent=this._handleEvent.bind(this),this._bindEvents(),attrs.mainPage&&this.setMainPage(attrs.mainPage),attrs.menuPage&&this.setMenuPage(attrs.menuPage),this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this));var unlock=this._doorLock.lock();window.setTimeout(function(){var maxDistance=this._normalizeMaxSlideDistanceAttr();this._logic.setMaxDistance(maxDistance),this._menuPage.css({opacity:1}),this._animator=this._getAnimatorOption(),this._animator.setup(this._element,this._mainPage,this._menuPage,{isRight:this._isRightMenu,width:this._attrs.maxSlideDistance||"90%"}),unlock()}.bind(this),400),scope.$on("$destroy",this._destroy.bind(this)),attrs.swipeable||this.setSwipeable(!0)},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},_onDeviceBackButton:function(event){this.isMenuOpened()?this.closeMenu():event.callParentHandler()},_onTap:function(){this.isMenuOpened()&&this.closeMenu()},_refreshMenuPageWidth:function(){var width="maxSlideDistance"in this._attrs?this._attrs.maxSlideDistance:"90%";this._animator&&this._animator.onResized({isOpened:this._logic.isOpened(),width:width})},_destroy:function(){this.emit("destroy"),this._deviceBackButtonHandler.destroy(),window.removeEventListener("resize",this._bindedOnWindowResize),this._mainPageHammer.off("tap",this._bindedOnTap),this._element=this._scope=this._attrs=null},_getAnimatorOption:function(){var animator=SlidingMenuView._animatorDict[this._attrs.type];return animator instanceof SlidingMenuAnimator||(animator=SlidingMenuView._animatorDict["default"]),animator.copy()},_onSwipeableChanged:function(swipeable){swipeable=""===swipeable||void 0===swipeable||"true"==swipeable,this.setSwipeable(swipeable)},setSwipeable:function(enabled){enabled?this._activateHammer():this._deactivateHammer()},_onWindowResize:function(){this._recalculateMAX(),this._refreshMenuPageWidth()},_onMaxSlideDistanceChanged:function(){this._recalculateMAX(),this._refreshMenuPageWidth()},_normalizeMaxSlideDistanceAttr:function(){var maxDistance=this._attrs.maxSlideDistance;if("maxSlideDistance"in this._attrs){if("string"!=typeof maxDistance)throw new Error("invalid state");-1!==maxDistance.indexOf("px",maxDistance.length-2)?maxDistance=parseInt(maxDistance.replace("px",""),10):maxDistance.indexOf("%",maxDistance.length-1)>0&&(maxDistance=maxDistance.replace("%",""),maxDistance=parseFloat(maxDistance)/100*this._mainPage[0].clientWidth)}else maxDistance=.9*this._mainPage[0].clientWidth;return maxDistance},_recalculateMAX:function(){var maxDistance=this._normalizeMaxSlideDistanceAttr();maxDistance&&this._logic.setMaxDistance(parseInt(maxDistance,10))},_activateHammer:function(){this._hammertime.on("touch dragleft dragright swipeleft swiperight release",this._boundHandleEvent)},_deactivateHammer:function(){this._hammertime.off("touch dragleft dragright swipeleft swiperight release",this._boundHandleEvent)},_bindEvents:function(){this._hammertime=new Hammer(this._element[0],{dragMinDistance:1})},_appendMainPage:function(pageUrl,templateHTML){var pageScope=this._scope.$new(),pageContent=angular.element(templateHTML),link=$compile(pageContent);this._mainPage.append(pageContent),this._currentPageElement&&(this._currentPageElement.remove(),this._currentPageScope.$destroy()),link(pageScope),this._currentPageElement=pageContent,this._currentPageScope=pageScope,this._currentPageUrl=pageUrl},_appendMenuPage:function(templateHTML){var pageScope=this._scope.$new(),pageContent=angular.element(templateHTML),link=$compile(pageContent);this._menuPage.append(pageContent),this._currentMenuPageScope&&(this._currentMenuPageScope.$destroy(),this._currentMenuPageElement.remove()),link(pageScope),this._currentMenuPageElement=pageContent,this._currentMenuPageScope=pageScope},setMenuPage:function(page,options){if(!page)throw new Error("cannot set undefined page");options=options||{},options.callback=options.callback||function(){};var self=this;$onsen.getPageHTMLAsync(page).then(function(html){self._appendMenuPage(angular.element(html)),options.closeMenu&&self.close(),options.callback()},function(){throw new Error("Page is not found: "+page)})},setMainPage:function(pageUrl,options){options=options||{},options.callback=options.callback||function(){};var done=function(){options.closeMenu&&this.close(),options.callback()}.bind(this);if(this.currentPageUrl===pageUrl)return void done();if(!pageUrl)throw new Error("cannot set undefined page");var self=this;$onsen.getPageHTMLAsync(pageUrl).then(function(html){self._appendMainPage(pageUrl,html),done()},function(){throw new Error("Page is not found: "+page)})},_handleEvent:function(event){if(!this._doorLock.isLocked())switch(this._isInsideIgnoredElement(event.target)&&this._deactivateHammer(),event.type){case"dragleft":case"dragright":if(this._logic.isClosed()&&!this._isInsideSwipeTargetArea(event))return;event.gesture.preventDefault();var deltaX=event.gesture.deltaX,deltaDistance=this._isRightMenu?-deltaX:deltaX,startEvent=event.gesture.startEvent;if("isOpened"in startEvent||(startEvent.isOpened=this._logic.isOpened()),0>deltaDistance&&this._logic.isClosed())break;if(deltaDistance>0&&this._logic.isOpened())break;var distance=startEvent.isOpened?deltaDistance+this._logic.getMaxDistance():deltaDistance;this._logic.translate(distance);break;case"swipeleft":if(event.gesture.preventDefault(),this._logic.isClosed()&&!this._isInsideSwipeTargetArea(event))return;this._isRightMenu?this.open():this.close(),event.gesture.stopDetect();break;case"swiperight":if(event.gesture.preventDefault(),this._logic.isClosed()&&!this._isInsideSwipeTargetArea(event))return;this._isRightMenu?this.close():this.open(),event.gesture.stopDetect();break;case"release":this._lastDistance=null,this._logic.shouldOpen()?this.open():this._logic.shouldClose()&&this.close()}},_isInsideIgnoredElement:function(element){do{if(element.getAttribute&&element.getAttribute("sliding-menu-ignore"))return!0;element=element.parentNode}while(element);return!1},_isInsideSwipeTargetArea:function(event){var x=event.gesture.center.pageX;"_swipeTargetWidth"in event.gesture.startEvent||(event.gesture.startEvent._swipeTargetWidth=this._getSwipeTargetWidth());var targetWidth=event.gesture.startEvent._swipeTargetWidth;return this._isRightMenu?this._mainPage[0].clientWidth-x<targetWidth:targetWidth>x},_getSwipeTargetWidth:function(){var targetWidth=this._attrs.swipeTargetWidth;"string"==typeof targetWidth&&(targetWidth=targetWidth.replace("px",""));var width=parseInt(targetWidth,10);return 0>width||!targetWidth?this._mainPage[0].clientWidth:width},closeMenu:function(){return this.close.apply(this,arguments)},close:function(options){options=options||{},options="function"==typeof options?{callback:options}:options,this._logic.isClosed()||(this.emit("preclose",{slidingMenu:this}),this._doorLock.waitUnlock(function(){this._logic.close(options)}.bind(this)))},_close:function(options){var callback=options.callback||function(){},unlock=this._doorLock.lock(),instant="none"==options.animation;this._animator.closeMenu(function(){unlock(),this._mainPage.children().css("pointer-events",""),this._mainPageHammer.off("tap",this._bindedOnTap),this.emit("postclose",{slidingMenu:this}),callback()}.bind(this),instant)},openMenu:function(){return this.open.apply(this,arguments)},open:function(options){options=options||{},options="function"==typeof options?{callback:options}:options,this.emit("preopen",{slidingMenu:this}),this._doorLock.waitUnlock(function(){this._logic.open(options)}.bind(this))},_open:function(options){var callback=options.callback||function(){},unlock=this._doorLock.lock(),instant="none"==options.animation;this._animator.openMenu(function(){unlock(),this._mainPage.children().css("pointer-events","none"),this._mainPageHammer.on("tap",this._bindedOnTap),this.emit("postopen",{slidingMenu:this}),callback()}.bind(this),instant)},toggle:function(options){this._logic.isClosed()?this.open(options):this.close(options)},toggleMenu:function(){return this.toggle.apply(this,arguments)},isMenuOpened:function(){return this._logic.isOpened()},_translate:function(event){this._animator.translateMenu(event)}});return SlidingMenuView._animatorDict={"default":new RevealSlidingMenuAnimator,overlay:new OverlaySlidingMenuAnimator,reveal:new RevealSlidingMenuAnimator,push:new PushSlidingMenuAnimator},SlidingMenuView.registerSlidingMenuAnimator=function(name,animator){if(!(animator instanceof SlidingMenuAnimator))throw new Error('"animator" param must be an instance of SlidingMenuAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(SlidingMenuView),SlidingMenuView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("SlidingMenuAnimator",function(){return Class.extend({setup:function(element,mainPage,menuPage,options){},onResized:function(options){},openMenu:function(callback){},closeClose:function(callback){},destroy:function(){},translateMenu:function(mainPage,menuPage,options){},copy:function(){throw new Error("Override copy method.")}})})}(),function(){"use strict";var module=angular.module("onsen");module.factory("SplitView",["$compile","RevealSlidingMenuAnimator","$onsen","$onsGlobal",function($compile,RevealSlidingMenuAnimator,$onsen,$onsGlobal){function isNumber(n){return!isNaN(parseFloat(n))&&isFinite(n)}var SPLIT_MODE=0,COLLAPSE_MODE=1,MAIN_PAGE_RATIO=.9,SplitView=Class.extend({init:function(scope,element,attrs){element.addClass("onsen-sliding-menu"),this._element=element,this._scope=scope,this._attrs=attrs,this._mainPage=angular.element(element[0].querySelector(".onsen-split-view__main")),this._secondaryPage=angular.element(element[0].querySelector(".onsen-split-view__secondary")),this._max=this._mainPage[0].clientWidth*MAIN_PAGE_RATIO,this._mode=SPLIT_MODE,this._doorLock=new DoorLock,this._doSplit=!1,this._doCollapse=!1,$onsGlobal.orientation.on("change",this._onResize.bind(this)),this._animator=new RevealSlidingMenuAnimator,this._element.css("display","none"),attrs.mainPage&&this.setMainPage(attrs.mainPage),attrs.secondaryPage&&this.setSecondaryPage(attrs.secondaryPage);var unlock=this._doorLock.lock();this._considerChangingCollapse(),this._setSize(),setTimeout(function(){this._element.css("display","block"),unlock()}.bind(this),1e3/60*2),scope.$on("$destroy",this._destroy.bind(this))},_appendSecondPage:function(templateHTML){var pageScope=this._scope.$new(),pageContent=$compile(templateHTML)(pageScope);this._secondaryPage.append(pageContent),this._currentSecondaryPageElement&&(this._currentSecondaryPageElement.remove(),this._currentSecondaryPageScope.$destroy()),this._currentSecondaryPageElement=pageContent,this._currentSecondaryPageScope=pageScope},_appendMainPage:function(templateHTML){var pageScope=this._scope.$new(),pageContent=$compile(templateHTML)(pageScope);this._mainPage.append(pageContent),this._currentPage&&(this._currentPage.remove(),this._currentPageScope.$destroy()),this._currentPage=pageContent,this._currentPageScope=pageScope},setSecondaryPage:function(page){if(!page)throw new Error("cannot set undefined page");$onsen.getPageHTMLAsync(page).then(function(html){this._appendSecondPage(angular.element(html.trim()))}.bind(this),function(){throw new Error("Page is not found: "+page)})},setMainPage:function(page){if(!page)throw new Error("cannot set undefined page");$onsen.getPageHTMLAsync(page).then(function(html){this._appendMainPage(angular.element(html.trim()))}.bind(this),function(){throw new Error("Page is not found: "+page)})},_onResize:function(){var lastMode=this._mode;this._considerChangingCollapse(),lastMode===COLLAPSE_MODE&&this._mode===COLLAPSE_MODE&&this._animator.onResized({isOpened:!1,width:"90%"}),this._max=this._mainPage[0].clientWidth*MAIN_PAGE_RATIO},_considerChangingCollapse:function(){var should=this._shouldCollapse();should&&this._mode!==COLLAPSE_MODE?(this._fireUpdateEvent(),this._doSplit?this._activateSplitMode():this._activateCollapseMode()):should||this._mode!==COLLAPSE_MODE||(this._fireUpdateEvent(),this._doCollapse?this._activateCollapseMode():this._activateSplitMode()),this._doCollapse=this._doSplit=!1},update:function(){this._fireUpdateEvent();var should=this._shouldCollapse();this._doSplit?this._activateSplitMode():this._doCollapse?this._activateCollapseMode():should?this._activateCollapseMode():should||this._activateSplitMode(),this._doSplit=this._doCollapse=!1},_getOrientation:function(){return $onsGlobal.orientation.isPortrait()?"portrait":"landscape"},getCurrentMode:function(){return this._mode===COLLAPSE_MODE?"collapse":"split"},_shouldCollapse:function(){var c="portrait";if("string"==typeof this._attrs.collapse&&(c=this._attrs.collapse.trim()),"portrait"==c)return $onsGlobal.orientation.isPortrait();if("landscape"==c)return $onsGlobal.orientation.isLandscape();if("width"==c.substr(0,5)){var num=c.split(" ")[1];num.indexOf("px")>=0&&(num=num.substr(0,num.length-2));var width=window.innerWidth;return isNumber(num)&&num>width}var mq=window.matchMedia(c);return mq.matches},_setSize:function(){if(this._mode===SPLIT_MODE){this._attrs.mainPageWidth||(this._attrs.mainPageWidth="70");var secondarySize=100-this._attrs.mainPageWidth.replace("%","");this._secondaryPage.css({width:secondarySize+"%",opacity:1}),this._mainPage.css({width:this._attrs.mainPageWidth+"%"}),this._mainPage.css("left",secondarySize+"%")}},_fireEvent:function(name){this.emit(name,{splitView:this,width:window.innerWidth,orientation:this._getOrientation()})},_fireUpdateEvent:function(){var that=this;this.emit("update",{splitView:this,shouldCollapse:this._shouldCollapse(),currentMode:this.getCurrentMode(),split:function(){that._doSplit=!0,that._doCollapse=!1},collapse:function(){that._doSplit=!1,that._doCollapse=!0},width:window.innerWidth,orientation:this._getOrientation()})},_activateCollapseMode:function(){this._mode!==COLLAPSE_MODE&&(this._fireEvent("precollapse"),this._secondaryPage.attr("style",""),this._mainPage.attr("style",""),this._mode=COLLAPSE_MODE,this._animator.setup(this._element,this._mainPage,this._secondaryPage,{isRight:!1,width:"90%"}),this._fireEvent("postcollapse"))},_activateSplitMode:function(){this._mode!==SPLIT_MODE&&(this._fireEvent("presplit"),this._animator.destroy(),this._secondaryPage.attr("style",""),this._mainPage.attr("style",""),this._mode=SPLIT_MODE,this._setSize(),this._fireEvent("postsplit"))},_destroy:function(){this.emit("destroy"),this._element=null,this._scope=null}});return MicroEvent.mixin(SplitView),SplitView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("SwitchView",["$onsen",function($onsen){var SwitchView=Class.extend({init:function(element,scope,attrs){this._element=element,this._checkbox=angular.element(element[0].querySelector("input[type=checkbox]")),this._scope=scope,attrs.$observe("disabled",function(disabled){element.attr("disabled")?this._checkbox.attr("disabled","disabled"):this._checkbox.removeAttr("disabled")}.bind(this)),this._checkbox.on("change",function(event){this.emit("change",{"switch":this,value:this._checkbox[0].checked,isInteractive:!0})}.bind(this))},isChecked:function(){return this._checkbox[0].checked},setChecked:function(isChecked){isChecked=!!isChecked,this._checkbox[0].checked!=isChecked&&(this._scope.model=isChecked,this._checkbox[0].checked=isChecked,this._scope.$evalAsync(),this.emit("change",{"switch":this,value:isChecked,isInteractive:!1}))},getCheckboxElement:function(){return this._checkbox[0]}});return MicroEvent.mixin(SwitchView),SwitchView}])}(),function(){"use strict;";var module=angular.module("onsen"); module.factory("TabbarAnimator",function(){var TabbarAnimator=Class.extend({apply:function(enterPage,leavePage,done){throw new Error("This method must be implemented.")}});return TabbarAnimator}),module.factory("TabbarNoneAnimator",["TabbarAnimator",function(TabbarAnimator){var TabbarNoneAnimator=TabbarAnimator.extend({apply:function(enterPage,leavePage,done){done()}});return TabbarNoneAnimator}]),module.factory("TabbarFadeAnimator",["TabbarAnimator",function(TabbarAnimator){var TabbarFadeAnimator=TabbarAnimator.extend({apply:function(enterPage,leavePage,done){animit.runAll(animit(enterPage[0]).queue({transform:"translate3D(0, 0, 0)",opacity:0}).queue({transform:"translate3D(0, 0, 0)",opacity:1},{duration:.4,timing:"linear"}).resetStyle().queue(function(callback){done(),callback()}),animit(leavePage[0]).queue({transform:"translate3D(0, 0, 0)",opacity:1}).queue({transform:"translate3D(0, 0, 0)",opacity:0},{duration:.4,timing:"linear"}))}});return TabbarFadeAnimator}]),module.factory("TabbarView",["$onsen","$compile","TabbarAnimator","TabbarNoneAnimator","TabbarFadeAnimator",function($onsen,$compile,TabbarAnimator,TabbarNoneAnimator,TabbarFadeAnimator){var TabbarView=Class.extend({_tabbarId:void 0,_tabItems:void 0,init:function(scope,element,attrs){this._scope=scope,this._element=element,this._attrs=attrs,this._tabbarId=Date.now(),this._tabItems=[],this._contentElement=angular.element(element[0].querySelector(".ons-tab-bar__content")),this._tabbarElement=angular.element(element[0].querySelector(".ons-tab-bar__footer")),this._scope.$on("$destroy",this._destroy.bind(this)),this._hasTopTabbar()&&this._prepareForTopTabbar()},_prepareForTopTabbar:function(){this._contentElement.attr("no-status-bar-fill",""),setImmediate(function(){this._contentElement.addClass("tab-bar--top__content"),this._tabbarElement.addClass("tab-bar--top")}.bind(this));var page=ons.findParentComponentUntil("ons-page",this._element[0]);if(page&&this._element.css("top",window.getComputedStyle(page.getContentElement(),null).getPropertyValue("padding-top")),$onsen.shouldFillStatusBar(this._element[0])){var fill=angular.element(document.createElement("div"));fill.addClass("tab-bar__status-bar-fill"),fill.css({width:"0px",height:"0px"}),this._element.prepend(fill)}},_hasTopTabbar:function(){return"top"===this._attrs.position},setActiveTab:function(index,options){options=options||{};var previousTabItem=this._tabItems[this.getActiveTabIndex()],selectedTabItem=this._tabItems[index];if(("undefined"!=typeof selectedTabItem.noReload||selectedTabItem.isPersistent())&&index===this.getActiveTabIndex())return this.emit("reactive",{index:index,tabItem:selectedTabItem}),!1;var needLoad=selectedTabItem.page&&!options.keepPage;if(!selectedTabItem)return!1;var canceled=!1;if(this.emit("prechange",{index:index,tabItem:selectedTabItem,cancel:function(){canceled=!0}}),canceled)return selectedTabItem.setInactive(),previousTabItem&&previousTabItem.setActive(),!1;if(selectedTabItem.setActive(),needLoad){var removeElement=!0;previousTabItem&&previousTabItem.isPersistent()&&(removeElement=!1,previousTabItem._pageElement=this._currentPageElement);var params={callback:function(){this.emit("postchange",{index:index,tabItem:selectedTabItem})}.bind(this),_removeElement:removeElement};options.animation&&(params.animation=options.animation),selectedTabItem.isPersistent()&&selectedTabItem._pageElement?this._loadPersistentPageDOM(selectedTabItem._pageElement,params):this._loadPage(selectedTabItem.page,params)}for(var i=0;i<this._tabItems.length;i++)this._tabItems[i]!=selectedTabItem?this._tabItems[i].setInactive():needLoad||this.emit("postchange",{index:index,tabItem:selectedTabItem});return!0},setTabbarVisibility:function(visible){this._scope.hideTabs=!visible,this._onTabbarVisibilityChanged()},_onTabbarVisibilityChanged:function(){this._hasTopTabbar()?this._scope.hideTabs?this._contentElement.css("top","0px"):this._contentElement.css("top",""):this._scope.hideTabs?this._contentElement.css("bottom","0px"):this._contentElement.css("bottom","")},addTabItem:function(tabItem){this._tabItems.push(tabItem)},getActiveTabIndex:function(){for(var tabItem,i=0;i<this._tabItems.length;i++)if(tabItem=this._tabItems[i],tabItem.isActive())return i;return-1},loadPage:function(page,options){return this._loadPage(page,options)},_loadPage:function(page,options){$onsen.getPageHTMLAsync(page).then(function(html){var pageElement=angular.element(html.trim());this._loadPageDOM(pageElement,options)}.bind(this),function(){throw new Error("Page is not found: "+page)})},_switchPage:function(element,options){if(this._currentPageElement){var oldPageElement=this._currentPageElement,oldPageScope=this._currentPageScope;this._currentPageElement=element,this._currentPageScope=element.data("_scope"),this._getAnimatorOption(options).apply(element,oldPageElement,function(){options._removeElement?(oldPageElement.remove(),oldPageScope.$destroy()):oldPageElement.css("display","none"),options.callback instanceof Function&&options.callback()})}else this._currentPageElement=element,this._currentPageScope=element.data("_scope"),options.callback instanceof Function&&options.callback()},_loadPageDOM:function(element,options){options=options||{};var pageScope=this._scope.$new(),link=$compile(element);this._contentElement.append(element);var pageContent=link(pageScope);pageScope.$evalAsync(),this._switchPage(pageContent,options)},_loadPersistentPageDOM:function(element,options){options=options||{},element.css("display","block"),this._switchPage(element,options)},_getAnimatorOption:function(options){var animationAttr=this._element.attr("animation")||"default";return TabbarView._animatorDict[options.animation||animationAttr]||TabbarView._animatorDict["default"]},_destroy:function(){this.emit("destroy"),this._element=this._scope=this._attrs=null}});return MicroEvent.mixin(TabbarView),TabbarView._animatorDict={"default":new TabbarNoneAnimator,none:new TabbarNoneAnimator,fade:new TabbarFadeAnimator},TabbarView.registerAnimator=function(name,animator){if(!(animator instanceof TabbarAnimator))throw new Error('"animator" param must be an instance of TabbarAnimator');this._animatorDict[name]=animator},TabbarView}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsAlertDialog",["$onsen","AlertDialogView",function($onsen,AlertDialogView){return{restrict:"E",replace:!1,scope:!0,transclude:!1,compile:function(element,attrs){var modifierTemplater=$onsen.generateModifierTemplater(attrs);element.addClass("alert-dialog "+modifierTemplater("alert-dialog--*"));var titleElement=angular.element(element[0].querySelector(".alert-dialog-title")),contentElement=angular.element(element[0].querySelector(".alert-dialog-content"));return titleElement.length&&titleElement.addClass(modifierTemplater("alert-dialog-title--*")),contentElement.length&&contentElement.addClass(modifierTemplater("alert-dialog-content--*")),{pre:function(scope,element,attrs){var alertDialog=new AlertDialogView(scope,element,attrs);$onsen.declareVarAttribute(attrs,alertDialog),$onsen.registerEventHandlers(alertDialog,"preshow prehide postshow posthide destroy"),$onsen.addModifierMethods(alertDialog,"alert-dialog--*",element),titleElement.length&&$onsen.addModifierMethods(alertDialog,"alert-dialog-title--*",titleElement),contentElement.length&&$onsen.addModifierMethods(alertDialog,"alert-dialog-content--*",contentElement),$onsen.isAndroid()&&alertDialog.addModifier("android"),element.data("ons-alert-dialog",alertDialog),scope.$on("$destroy",function(){alertDialog._events=void 0,$onsen.removeModifierMethods(alertDialog),element.data("ons-alert-dialog",void 0),element=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsBackButton",["$onsen","$compile","GenericView","ComponentCleaner",function($onsen,$compile,GenericView,ComponentCleaner){return{restrict:"E",replace:!1,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/back_button.tpl",transclude:!0,scope:!0,link:{pre:function(scope,element,attrs,controller,transclude){var backButton=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,backButton),element.data("ons-back-button",backButton),scope.$on("$destroy",function(){backButton._events=void 0,$onsen.removeModifierMethods(backButton),element.data("ons-back-button",void 0),element=null}),scope.modifierTemplater=$onsen.generateModifierTemplater(attrs);var navigator=ons.findParentComponentUntil("ons-navigator",element);scope.$watch(function(){return navigator.pages.length},function(nbrOfPages){scope.showBackButton=nbrOfPages>1}),$onsen.addModifierMethods(backButton,"toolbar-button--*",element.children()),transclude(scope,function(clonedElement){clonedElement[0]&&element[0].querySelector(".back-button__label").appendChild(clonedElement[0])}),ComponentCleaner.onDestroy(scope,function(){ComponentCleaner.destroyScope(scope),ComponentCleaner.destroyAttributes(attrs),element=null,scope=null,attrs=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsBottomToolbar",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,transclude:!1,scope:!1,compile:function(element,attrs){var modifierTemplater=$onsen.generateModifierTemplater(attrs),inline="undefined"!=typeof attrs.inline;return element.addClass("bottom-bar"),element.addClass(modifierTemplater("bottom-bar--*")),element.css({"z-index":0}),inline&&element.css("position","static"),{pre:function(scope,element,attrs){var bottomToolbar=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,bottomToolbar),element.data("ons-bottomToolbar",bottomToolbar),scope.$on("$destroy",function(){bottomToolbar._events=void 0,$onsen.removeModifierMethods(bottomToolbar),element.data("ons-bottomToolbar",void 0),element=null}),$onsen.addModifierMethods(bottomToolbar,"bottom-bar--*",element);var pageView=element.inheritedData("ons-page");pageView&&!inline&&pageView.registerBottomToolbar(element)},post:function(scope,element,attrs){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsButton",["$onsen","ButtonView",function($onsen,ButtonView){return{restrict:"E",replace:!1,transclude:!0,scope:{animation:"@"},templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/button.tpl",link:function(scope,element,attrs,_,transclude){var button=new ButtonView(scope,element,attrs);$onsen.declareVarAttribute(attrs,button),element.data("ons-button",button),scope.$on("$destroy",function(){button._events=void 0,$onsen.removeModifierMethods(button),element.data("ons-button",void 0),element=null});var initialAnimation="slide-left";if(scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),element.addClass("button effeckt-button"),element.addClass(scope.modifierTemplater("button--*")),element.addClass(initialAnimation),$onsen.addModifierMethods(button,"button--*",element),transclude(scope.$parent,function(cloned){angular.element(element[0].querySelector(".ons-button-inner")).append(cloned)}),attrs.ngController)throw new Error("This element can't accept ng-controller directive.");scope.item={},scope.item.animation=initialAnimation,scope.$watch("animation",function(newAnimation){newAnimation&&(scope.item.animation&&element.removeClass(scope.item.animation),scope.item.animation=newAnimation,element.addClass(scope.item.animation))}),attrs.$observe("shouldSpin",function(shouldSpin){"true"===shouldSpin?element.attr("data-loading",!0):element.removeAttr("data-loading")}),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,attrs:attrs,element:element}),scope=element=attrs=null}),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsCarousel",["$onsen","CarouselView",function($onsen,CarouselView){return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){var templater=$onsen.generateModifierTemplater(attrs);return element.addClass(templater("carousel--*")),function(scope,element,attrs){var carousel=new CarouselView(scope,element,attrs);element.data("ons-carousel",carousel),$onsen.registerEventHandlers(carousel,"postchange refresh overscroll destroy"),$onsen.declareVarAttribute(attrs,carousel),scope.$on("$destroy",function(){carousel._events=void 0,element.data("ons-carousel",void 0),element=null}),element[0].hasAttribute("auto-refresh")&&scope.$watch(function(){return element[0].childNodes.length},function(){setImmediate(function(){carousel.refresh()})}),setImmediate(function(){carousel.refresh()}),$onsen.fireComponentEvent(element[0],"init")}}}}]),module.directive("onsCarouselItem",["$onsen",function($onsen){return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){var templater=$onsen.generateModifierTemplater(attrs);return element.addClass(templater("carousel-item--*")),element.css("width","100%"),function(scope,element,attrs){}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsCol",["$timeout","$onsen",function($timeout,$onsen){return{restrict:"E",replace:!1,transclude:!1,scope:!1,compile:function(element,attrs,transclude){return element.addClass("col ons-col-inner"),function(scope,element,attrs){function updateAlign(align){"top"===align||"center"===align||"bottom"===align?(element.removeClass("col-top col-center col-bottom"),element.addClass("col-"+align)):element.removeClass("col-top col-center col-bottom")}function updateWidth(width){"string"==typeof width?(width=(""+width).trim(),width=width.match(/^\d+$/)?width+"%":width,element.css({"-webkit-box-flex":"0","-webkit-flex":"0 0 "+width,"-moz-box-flex":"0","-moz-flex":"0 0 "+width,"-ms-flex":"0 0 "+width,flex:"0 0 "+width,"max-width":width})):element.removeAttr("style")}attrs.$observe("align",function(align){updateAlign(align)}),attrs.$observe("width",function(width){updateWidth(width)}),attrs.$observe("size",function(size){attrs.width||updateWidth(size)}),updateAlign(attrs.align),updateWidth(attrs.size&&!attrs.width?attrs.size:attrs.width),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,element:element,attrs:attrs}),element=attrs=scope=null}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsDialog",["$onsen","DialogView",function($onsen,DialogView){return{restrict:"E",replace:!1,scope:!0,transclude:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/dialog.tpl",compile:function(element,attrs,transclude){return element[0].setAttribute("no-status-bar-fill",""),{pre:function(scope,element,attrs){transclude(scope,function(clone){angular.element(element[0].querySelector(".dialog")).append(clone)});var dialog=new DialogView(scope,element,attrs);scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),$onsen.addModifierMethods(dialog,"dialog--*",angular.element(element[0].querySelector(".dialog"))),$onsen.declareVarAttribute(attrs,dialog),$onsen.registerEventHandlers(dialog,"preshow prehide postshow posthide destroy"),element.data("ons-dialog",dialog),scope.$on("$destroy",function(){dialog._events=void 0,$onsen.removeModifierMethods(dialog),element.data("ons-dialog",void 0),element=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsDummyForInit",["$rootScope",function($rootScope){var isReady=!1;return{restrict:"E",replace:!1,link:{post:function(scope,element){isReady||(isReady=!0,$rootScope.$broadcast("$ons-ready")),element.remove()}}}}])}(),function(){"use strict";var EVENTS="drag dragleft dragright dragup dragdown hold release swipe swipeleft swiperight swipeup swipedown tap doubletap touch transform pinch pinchin pinchout rotate".split(/ +/);angular.module("onsen").directive("onsGestureDetector",["$onsen",function($onsen){function titlize(str){return str.charAt(0).toUpperCase()+str.slice(1)}var scopeDef=EVENTS.reduce(function(dict,name){return dict["ng"+titlize(name)]="&",dict},{});return{restrict:"E",scope:scopeDef,replace:!1,transclude:!0,compile:function(element,attrs){return function(scope,element,attrs,controller,transclude){function handleEvent(event){var attr="ng"+titlize(event.type);attr in scopeDef&&scope[attr]({$event:event})}transclude(scope.$parent,function(cloned){element.append(cloned)});var hammer=new Hammer(element[0]);hammer.on(EVENTS.join(" "),handleEvent),$onsen.cleaner.onDestroy(scope,function(){hammer.off(EVENTS.join(" "),handleEvent),$onsen.clearComponent({scope:scope,element:element,attrs:attrs}),hammer.element=scope=element=attrs=null}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";function cleanClassAttribute(element){var classList=(""+element.attr("class")).split(/ +/).filter(function(classString){return"fa"!==classString&&"fa-"!==classString.substring(0,3)&&"ion-"!==classString.substring(0,4)});element.attr("class",classList.join(" "))}function buildClassAndStyle(attrs){var classList=["ons-icon"],style={};0===attrs.icon.indexOf("ion-")?(classList.push(attrs.icon),classList.push("ons-icon--ion")):0===attrs.icon.indexOf("fa-")?(classList.push(attrs.icon),classList.push("fa")):(classList.push("fa"),classList.push("fa-"+attrs.icon));var size=""+attrs.size;return size.match(/^[1-5]x|lg$/)?classList.push("fa-"+size):"string"==typeof attrs.size?style["font-size"]=size:classList.push("fa-lg"),{"class":classList.join(" "),style:style}}var module=angular.module("onsen");module.directive("onsIcon",["$onsen",function($onsen){return{restrict:"E",replace:!1,transclude:!1,link:function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");var update=function(){cleanClassAttribute(element);var builded=buildClassAndStyle(attrs);element.css(builded.style),element.addClass(builded["class"])},builded=buildClassAndStyle(attrs);element.css(builded.style),element.addClass(builded["class"]),attrs.$observe("icon",update),attrs.$observe("size",update),attrs.$observe("fixedWidth",update),attrs.$observe("rotate",update),attrs.$observe("flip",update),attrs.$observe("spin",update),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,element:element,attrs:attrs}),element=scope=attrs=null}),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsIfOrientation",["$onsen","$onsGlobal",function($onsen,$onsGlobal){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:function(element){return element.css("display","none"),function(scope,element,attrs){function update(){var userOrientation=(""+attrs.onsIfOrientation).toLowerCase(),orientation=getLandscapeOrPortrait();("portrait"===userOrientation||"landscape"===userOrientation)&&(userOrientation===orientation?element.css("display",""):element.css("display","none"))}function getLandscapeOrPortrait(){return $onsGlobal.orientation.isPortrait()?"portrait":"landscape"}element.addClass("ons-if-orientation-inner"),attrs.$observe("onsIfOrientation",update),$onsGlobal.orientation.on("change",update),update(),$onsen.cleaner.onDestroy(scope,function(){$onsGlobal.orientation.off("change",update),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),element=scope=attrs=null})}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsIfPlatform",["$onsen",function($onsen){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:function(element){function getPlatformString(){if(navigator.userAgent.match(/Android/i))return"android";if(navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/RIM Tablet OS/i)||navigator.userAgent.match(/BB10/i))return"blackberry";if(navigator.userAgent.match(/iPhone|iPad|iPod/i))return"ios";if(navigator.userAgent.match(/IEMobile/i))return"windows";var isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0;if(isOpera)return"opera";var isFirefox="undefined"!=typeof InstallTrigger;if(isFirefox)return"firefox";var isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0;if(isSafari)return"safari";var isChrome=!!window.chrome&&!isOpera;if(isChrome)return"chrome";var isIE=!!document.documentMode;return isIE?"ie":"unknown"}element.addClass("ons-if-platform-inner"),element.css("display","none");var platform=getPlatformString();return function(scope,element,attrs){function update(){attrs.onsIfPlatform.toLowerCase()===platform.toLowerCase()?element.css("display","block"):element.css("display","none")}attrs.$observe("onsIfPlatform",function(userPlatform){userPlatform&&update()}),update(),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),element=scope=attrs=null})}}}}])}(),function(){"use strict";var module=angular.module("onsen"),compileFunction=function(show,$onsen){return function(element){return function(scope,element,attrs){var dispShow=show?"block":"none",dispHide=show?"none":"block",onShow=function(){element.css("display",dispShow)},onHide=function(){element.css("display",dispHide)},onInit=function(e){e.visible?onShow():onHide()};ons.softwareKeyboard.on("show",onShow),ons.softwareKeyboard.on("hide",onHide),ons.softwareKeyboard.on("init",onInit),ons.softwareKeyboard._visible?onShow():onHide(),$onsen.cleaner.onDestroy(scope,function(){ons.softwareKeyboard.off("show",onShow),ons.softwareKeyboard.off("hide",onHide),ons.softwareKeyboard.off("init",onInit),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),element=scope=attrs=null})}}};module.directive("onsKeyboardActive",["$onsen",function($onsen){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:compileFunction(!0,$onsen)}}]),module.directive("onsKeyboardInactive",["$onsen",function($onsen){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:compileFunction(!1,$onsen)}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsLazyRepeat",["$onsen","LazyRepeatView",function($onsen,LazyRepeatView){return{restrict:"A",replace:!1,priority:1e3,transclude:"element",compile:function(element,attrs,linker){return function(scope,element,attrs){new LazyRepeatView(scope,element,attrs,linker);scope.$on("$destroy",function(){scope=element=attrs=linker=null})}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsList",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",scope:!1,replace:!1,transclude:!1,compile:function(element,attrs){return function(scope,element,attrs){var list=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,list),element.data("ons-list",list),scope.$on("$destroy",function(){list._events=void 0,$onsen.removeModifierMethods(list),element.data("ons-list",void 0),element=null});var templater=$onsen.generateModifierTemplater(attrs);element.addClass("list ons-list-inner"),element.addClass(templater("list--*")),$onsen.addModifierMethods(list,"list--*",element),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsListHeader",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,transclude:!1,compile:function(){return function(scope,element,attrs){var listHeader=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,listHeader),element.data("ons-listHeader",listHeader),scope.$on("$destroy",function(){listHeader._events=void 0,$onsen.removeModifierMethods(listHeader),element.data("ons-listHeader",void 0),element=null});var templater=$onsen.generateModifierTemplater(attrs);element.addClass("list__header ons-list-header-inner"),element.addClass(templater("list__header--*")),$onsen.addModifierMethods(listHeader,"list__header--*",element),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsListItem",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,transclude:!1,compile:function(){return function(scope,element,attrs){var listItem=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,listItem),element.data("ons-list-item",listItem),scope.$on("$destroy",function(){listItem._events=void 0,$onsen.removeModifierMethods(listItem),element.data("ons-list-item",void 0),element=null});var templater=$onsen.generateModifierTemplater(attrs);element.addClass("list__item ons-list-item-inner"),element.addClass(templater("list__item--*")),$onsen.addModifierMethods(listItem,"list__item--*",element),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsLoadingPlaceholder",["$onsen","$compile",function($onsen,$compile){return{restrict:"A",replace:!1,transclude:!1,scope:!1,link:function(scope,element,attrs){if(!attrs.onsLoadingPlaceholder.length)throw Error("Must define page to load.");setImmediate(function(){$onsen.getPageHTMLAsync(attrs.onsLoadingPlaceholder).then(function(html){html=html.trim().replace(/^<ons-page>/,"").replace(/<\/ons-page>$/,"");var div=document.createElement("div");div.innerHTML=html;var newElement=angular.element(div);newElement.css("display","none"),element.append(newElement),$compile(newElement)(scope);for(var i=element[0].childNodes.length-1;i>=0;i--){var e=element[0].childNodes[i];e!==div&&element[0].removeChild(e)}newElement.css("display","block")})})}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsModal",["$onsen","ModalView",function($onsen,ModalView){function compile(element,attrs){var modifierTemplater=$onsen.generateModifierTemplater(attrs),html=element[0].innerHTML;element[0].innerHTML="";var wrapper=angular.element("<div></div>");wrapper.addClass("modal__content"),wrapper.addClass(modifierTemplater("modal--*__content")),element.css("display","none"),element.addClass("modal"),element.addClass(modifierTemplater("modal--*")),wrapper[0].innerHTML=html,element.append(wrapper)}return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){return compile(element,attrs),{pre:function(scope,element,attrs){var page=element.inheritedData("ons-page");page&&page.registerExtraElement(element);var modal=new ModalView(scope,element);$onsen.addModifierMethods(modal,"modal--*",element),$onsen.addModifierMethods(modal,"modal--*__content",element.children()),$onsen.declareVarAttribute(attrs,modal),element.data("ons-modal",modal),scope.$on("$destroy",function(){modal._events=void 0,$onsen.removeModifierMethods(modal),element.data("ons-modal",void 0)})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsNavigator",["$compile","NavigatorView","$onsen",function($compile,NavigatorView,$onsen){return{restrict:"E",transclude:!1,scope:!0,compile:function(element){var html=$onsen.normalizePageHTML(element.html());return element.contents().remove(),{pre:function(scope,element,attrs,controller){var navigator=new NavigatorView(scope,element,attrs);if($onsen.declareVarAttribute(attrs,navigator),$onsen.registerEventHandlers(navigator,"prepush prepop postpush postpop destroy"),attrs.page)navigator.pushPage(attrs.page,{});else{var pageScope=navigator._createPageScope(),pageElement=angular.element(html),linkScope=$compile(pageElement),link=function(){linkScope(pageScope)};navigator._pushPageDOM("",pageElement,link,pageScope,{}),pageElement=null}element.data("ons-navigator",navigator),element.data("_scope",scope),scope.$on("$destroy",function(){element.data("_scope",void 0),navigator._events=void 0,element.data("ons-navigator",void 0),element=null})},post:function(scope,element,attrs){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsPage",["$onsen","PageView",function($onsen,PageView){function firePageInitEvent(element){var i=0,f=function(){if(!(i++<5))throw new Error('Fail to fire "pageinit" event. Attach "ons-page" element to the document after initialization.');isAttached(element)?(fillStatusBar(element),$onsen.fireComponentEvent(element,"init"),fireActualPageInitEvent(element)):setImmediate(f)};f()}function fireActualPageInitEvent(element){var event=document.createEvent("HTMLEvents");event.initEvent("pageinit",!0,!0),element.dispatchEvent(event)}function fillStatusBar(element){if($onsen.shouldFillStatusBar(element)){var fill=angular.element(document.createElement("div"));fill.addClass("page__status-bar-fill"),fill.css({width:"0px",height:"0px"}),angular.element(element).prepend(fill)}}function isAttached(element){return document.documentElement===element?!0:element.parentNode?isAttached(element.parentNode):!1}function preLink(scope,element,attrs,controller,transclude){var page=new PageView(scope,element,attrs);$onsen.declareVarAttribute(attrs,page),element.data("ons-page",page);var modifierTemplater=$onsen.generateModifierTemplater(attrs),template="page--*";element.addClass("page "+modifierTemplater(template)),$onsen.addModifierMethods(page,template,element);var pageContent=angular.element(element[0].querySelector(".page__content"));pageContent.addClass(modifierTemplater("page--*__content")),pageContent=null;var pageBackground=angular.element(element[0].querySelector(".page__background"));pageBackground.addClass(modifierTemplater("page--*__background")),pageBackground=null,element.data("_scope",scope),$onsen.cleaner.onDestroy(scope,function(){element.data("_scope",void 0),page._events=void 0,$onsen.removeModifierMethods(page),element.data("ons-page",void 0),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),scope=element=attrs=null})}function postLink(scope,element,attrs){firePageInitEvent(element[0])}return{restrict:"E",transclude:!1,scope:!1,compile:function(element){var children=element.children().remove(),content=angular.element('<div class="page__content ons-page-inner"></div>').append(children),background=angular.element('<div class="page__background"></div>');if(element.attr("style")&&(background.attr("style",element.attr("style")),element.attr("style","")),element.append(background),Modernizr.csstransforms3d)element.append(content);else{content.css("overflow","visible");var wrapper=angular.element("<div></div>");wrapper.append(children),content.append(wrapper),element.append(content),wrapper=null;var scroller=new IScroll(content[0],{momentum:!0,bounce:!0,hScrollbar:!1,vScrollbar:!1,preventDefault:!1}),offset=10;scroller.on("scrollStart",function(e){var scrolled=scroller.y-offset;scrolled<scroller.maxScrollY+40&&scroller.refresh()})}return content=null,background=null,children=null,{pre:preLink,post:postLink}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsPopover",["$onsen","PopoverView",function($onsen,PopoverView){return{restrict:"E",replace:!1,transclude:!0,scope:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/popover.tpl",compile:function(element,attrs,transclude){return{pre:function(scope,element,attrs){transclude(scope,function(clone){angular.element(element[0].querySelector(".popover__content")).append(clone)});var popover=new PopoverView(scope,element,attrs);$onsen.declareVarAttribute(attrs,popover),$onsen.registerEventHandlers(popover,"preshow prehide postshow posthide destroy"),element.data("ons-popover",popover),scope.$on("$destroy",function(){popover._events=void 0,$onsen.removeModifierMethods(popover),element.data("ons-popover",void 0),element=null}),scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),$onsen.addModifierMethods(popover,"popover--*",angular.element(element[0].querySelector(".popover"))), $onsen.addModifierMethods(popover,"popover__content--*",angular.element(element[0].querySelector(".popover__content"))),$onsen.isAndroid()&&setImmediate(function(){popover.addModifier("android")}),scope.direction="up",scope.arrowPosition="bottom"},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsPullHook",["$onsen","PullHookView",function($onsen,PullHookView){return{restrict:"E",replace:!1,scope:!0,compile:function(element,attrs){return{pre:function(scope,element,attrs){var pullHook=new PullHookView(scope,element,attrs);$onsen.declareVarAttribute(attrs,pullHook),$onsen.registerEventHandlers(pullHook,"changestate destroy"),element.data("ons-pull-hook",pullHook),scope.$on("$destroy",function(){pullHook._events=void 0,element.data("ons-pull-hook",void 0),scope=element=attrs=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsRow",["$onsen","$timeout",function($onsen,$timeout){return{restrict:"E",replace:!1,transclude:!1,scope:!1,compile:function(element,attrs){return element.addClass("row ons-row-inner"),function(scope,element,attrs){function update(){var align=(""+attrs.align).trim();("top"===align||"center"===align||"bottom"===align)&&(element.removeClass("row-bottom row-center row-top"),element.addClass("row-"+align))}attrs.$observe("align",function(align){update()}),update(),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsScroller",["$onsen","$timeout",function($onsen,$timeout){return{restrict:"E",replace:!1,transclude:!0,scope:{onScrolled:"&",infinitScrollEnable:"="},compile:function(element,attrs){element.addClass("ons-scroller").children().remove();return function(scope,element,attrs,controller,transclude){if(attrs.ngController)throw new Error('"ons-scroller" can\'t accept "ng-controller" directive.');var wrapper=angular.element("<div></div>");wrapper.addClass("ons-scroller__content ons-scroller-inner"),element.append(wrapper),transclude(scope.$parent,function(cloned){wrapper.append(cloned),wrapper=null});var scrollWrapper;scrollWrapper=element[0];var offset=parseInt(attrs.threshold)||10;scope.onScrolled&&scrollWrapper.addEventListener("scroll",function(){if(scope.infinitScrollEnable){var scrollTopAndOffsetHeight=scrollWrapper.scrollTop+scrollWrapper.offsetHeight,scrollHeightMinusOffset=scrollWrapper.scrollHeight-offset;scrollTopAndOffsetHeight>=scrollHeightMinusOffset&&scope.onScrolled()}}),Modernizr.csstransforms3d||$timeout(function(){var iScroll=new IScroll(scrollWrapper,{momentum:!0,bounce:!0,hScrollbar:!1,vScrollbar:!1,preventDefault:!1});iScroll.on("scrollStart",function(e){var scrolled=iScroll.y-offset;scrolled<iScroll.maxScrollY+40&&iScroll.refresh()}),scope.onScrolled&&iScroll.on("scrollEnd",function(e){var scrolled=iScroll.y-offset;scrolled<iScroll.maxScrollY&&scope.onScrolled()})},500),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsSlidingMenu",["$compile","SlidingMenuView","$onsen",function($compile,SlidingMenuView,$onsen){return{restrict:"E",replace:!1,transclude:!1,scope:!0,compile:function(element,attrs){var main=element[0].querySelector(".main"),menu=element[0].querySelector(".menu");if(main)var mainHtml=angular.element(main).remove().html().trim();if(menu)var menuHtml=angular.element(menu).remove().html().trim();return function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");element.append(angular.element("<div></div>").addClass("onsen-sliding-menu__menu ons-sliding-menu-inner")),element.append(angular.element("<div></div>").addClass("onsen-sliding-menu__main ons-sliding-menu-inner"));var slidingMenu=new SlidingMenuView(scope,element,attrs);$onsen.registerEventHandlers(slidingMenu,"preopen preclose postopen postclose destroy"),mainHtml&&!attrs.mainPage&&slidingMenu._appendMainPage(null,mainHtml),menuHtml&&!attrs.menuPage&&slidingMenu._appendMenuPage(menuHtml),$onsen.declareVarAttribute(attrs,slidingMenu),element.data("ons-sliding-menu",slidingMenu),element.data("_scope",scope),scope.$on("$destroy",function(){element.data("_scope",void 0),slidingMenu._events=void 0,element.data("ons-sliding-menu",void 0)}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsSplitView",["$compile","SplitView","$onsen",function($compile,SplitView,$onsen){return{restrict:"E",replace:!1,transclude:!1,scope:!0,compile:function(element,attrs){var mainPage=element[0].querySelector(".main-page"),secondaryPage=element[0].querySelector(".secondary-page");if(mainPage)var mainHtml=angular.element(mainPage).remove().html().trim();if(secondaryPage)var secondaryHtml=angular.element(secondaryPage).remove().html().trim();return function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");element.append(angular.element("<div></div>").addClass("onsen-split-view__secondary full-screen ons-split-view-inner")),element.append(angular.element("<div></div>").addClass("onsen-split-view__main full-screen ons-split-view-inner"));var splitView=new SplitView(scope,element,attrs);mainHtml&&!attrs.mainPage&&splitView._appendMainPage(mainHtml),secondaryHtml&&!attrs.secondaryPage&&splitView._appendSecondPage(secondaryHtml),$onsen.declareVarAttribute(attrs,splitView),$onsen.registerEventHandlers(splitView,"update presplit precollapse postsplit postcollapse destroy"),element.data("ons-split-view",splitView),element.data("_scope",scope),scope.$on("$destroy",function(){element.data("_scope",void 0),splitView._events=void 0,element.data("ons-split-view",void 0)}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsSwitch",["$onsen","$parse","SwitchView",function($onsen,$parse,SwitchView){return{restrict:"E",replace:!1,transclude:!1,scope:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/switch.tpl",compile:function(element){return function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");var switchView=new SwitchView(element,scope,attrs),checkbox=angular.element(element[0].querySelector("input[type=checkbox]"));scope.modifierTemplater=$onsen.generateModifierTemplater(attrs);var label=element.children(),input=angular.element(label.children()[0]),toggle=angular.element(label.children()[1]);if($onsen.addModifierMethods(switchView,"switch--*",label),$onsen.addModifierMethods(switchView,"switch--*__input",input),$onsen.addModifierMethods(switchView,"switch--*__toggle",toggle),attrs.$observe("checked",function(checked){scope.model=!!element.attr("checked")}),attrs.$observe("name",function(name){element.attr("name")&&checkbox.attr("name",name)}),attrs.ngModel){var set=$parse(attrs.ngModel).assign;scope.$parent.$watch(attrs.ngModel,function(value){scope.model=value}),scope.$watch("model",function(to,from){set(scope.$parent,to),to!==from&&scope.$eval(attrs.ngChange)})}$onsen.declareVarAttribute(attrs,switchView),element.data("ons-switch",switchView),$onsen.cleaner.onDestroy(scope,function(){switchView._events=void 0,$onsen.removeModifierMethods(switchView),element.data("ons-switch",void 0),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),checkbox=element=attrs=scope=null}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";function tab($onsen,$compile){return{restrict:"E",transclude:!0,scope:{page:"@",active:"@",icon:"@",activeIcon:"@",label:"@",noReload:"@",persistent:"@"},templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/tab.tpl",compile:function(element,attrs){return element.addClass("tab-bar__item"),function(scope,element,attrs,controller,transclude){var tabbarView=element.inheritedData("ons-tabbar");if(!tabbarView)throw new Error("This ons-tab element is must be child of ons-tabbar element.");element.addClass(tabbarView._scope.modifierTemplater("tab-bar--*__item")),element.addClass(tabbarView._scope.modifierTemplater("tab-bar__item--*")),transclude(scope.$parent,function(cloned){var wrapper=angular.element(element[0].querySelector(".tab-bar-inner"));if(attrs.icon||attrs.label||!cloned[0]){var innerElement=angular.element("<div>"+defaultInnerTemplate+"</div>").children();wrapper.append(innerElement),$compile(innerElement)(scope)}else wrapper.append(cloned)});var radioButton=element[0].querySelector("input");scope.tabbarModifierTemplater=tabbarView._scope.modifierTemplater,scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),scope.tabbarId=tabbarView._tabbarId,scope.tabIcon=scope.icon,tabbarView.addTabItem(scope),scope.setActive=function(){element.addClass("active"),radioButton.checked=!0,scope.activeIcon&&(scope.tabIcon=scope.activeIcon),angular.element(element[0].querySelectorAll("[ons-tab-inactive]")).css("display","none"),angular.element(element[0].querySelectorAll("[ons-tab-active]")).css("display","inherit")},scope.setInactive=function(){element.removeClass("active"),radioButton.checked=!1,scope.tabIcon=scope.icon,angular.element(element[0].querySelectorAll("[ons-tab-inactive]")).css("display","inherit"),angular.element(element[0].querySelectorAll("[ons-tab-active]")).css("display","none")},scope.isPersistent=function(){return"undefined"!=typeof scope.persistent},scope.isActive=function(){return element.hasClass("active")},scope.tryToChange=function(){tabbarView.setActiveTab(tabbarView._tabItems.indexOf(scope))},scope.active&&tabbarView.setActiveTab(tabbarView._tabItems.indexOf(scope)),$onsen.fireComponentEvent(element[0],"init")}}}}var module=angular.module("onsen");module.directive("onsTab",tab),module.directive("onsTabbarItem",tab);var defaultInnerTemplate='<div ng-if="icon != undefined" class="tab-bar__icon"><ons-icon icon="{{tabIcon}}" style="font-size: 28px; line-height: 34px; vertical-align: top;"></ons-icon></div><div ng-if="label" class="tab-bar__label">{{label}}</div>';tab.$inject=["$onsen","$compile"]}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsTabbar",["$onsen","$compile","TabbarView",function($onsen,$compile,TabbarView){return{restrict:"E",replace:!1,transclude:!0,scope:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/tab_bar.tpl",link:function(scope,element,attrs,controller,transclude){scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),scope.selectedTabItem={source:""},attrs.$observe("hideTabs",function(hide){var visible="true"!==hide;tabbarView.setTabbarVisibility(visible)});var tabbarView=new TabbarView(scope,element,attrs);$onsen.addModifierMethods(tabbarView,"tab-bar--*",angular.element(element.children()[1])),$onsen.registerEventHandlers(tabbarView,"reactive prechange postchange destroy"),scope.tabbarId=tabbarView._tabbarId,element.data("ons-tabbar",tabbarView),$onsen.declareVarAttribute(attrs,tabbarView),transclude(scope,function(cloned){angular.element(element[0].querySelector(".ons-tabbar-inner")).append(cloned)}),scope.$on("$destroy",function(){tabbarView._events=void 0,$onsen.removeModifierMethods(tabbarView),element.data("ons-tabbar",void 0)}),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsTemplate",["$onsen","$templateCache",function($onsen,$templateCache){return{restrict:"E",transclude:!1,priority:1e3,terminal:!0,compile:function(element){$templateCache.put(element.attr("id"),element.remove().html()),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";function ensureLeftContainer(element,modifierTemplater){var container=element[0].querySelector(".left");return container||(container=document.createElement("div"),container.setAttribute("class","left"),container.innerHTML="&nbsp;"),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),angular.element(container).addClass("navigation-bar__left").addClass(modifierTemplater("navigation-bar--*__left")),container}function ensureCenterContainer(element,modifierTemplater){var container=element[0].querySelector(".center");return container||(container=document.createElement("div"),container.setAttribute("class","center")),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),angular.element(container).addClass("navigation-bar__title navigation-bar__center").addClass(modifierTemplater("navigation-bar--*__center")),container}function ensureRightContainer(element,modifierTemplater){var container=element[0].querySelector(".right");return container||(container=document.createElement("div"),container.setAttribute("class","right"),container.innerHTML="&nbsp;"),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),angular.element(container).addClass("navigation-bar__right").addClass(modifierTemplater("navigation-bar--*__right")),container}function hasCenterClassElementOnly(element){for(var child,hasCenter=!1,hasOther=!1,children=element.contents(),i=0;i<children.length;i++)child=angular.element(children[i]),child.hasClass("center")?hasCenter=!0:(child.hasClass("left")||child.hasClass("right"))&&(hasOther=!0);return hasCenter&&!hasOther}function ensureToolbarItemElements(element,modifierTemplater){var center;if(hasCenterClassElementOnly(element))center=ensureCenterContainer(element,modifierTemplater),element.contents().remove(),element.append(center);else{center=ensureCenterContainer(element,modifierTemplater);var left=ensureLeftContainer(element,modifierTemplater),right=ensureRightContainer(element,modifierTemplater);element.contents().remove(),element.append(angular.element([left,center,right]))}}var module=angular.module("onsen");module.directive("onsToolbar",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){var shouldAppendAndroidModifier=ons.platform.isAndroid()&&!element[0].hasAttribute("fixed-style"),modifierTemplater=$onsen.generateModifierTemplater(attrs,shouldAppendAndroidModifier?["android"]:[]),inline="undefined"!=typeof attrs.inline;return element.addClass("navigation-bar"),element.addClass(modifierTemplater("navigation-bar--*")),inline||element.css({position:"absolute","z-index":"10000",left:"0px",right:"0px",top:"0px"}),ensureToolbarItemElements(element,modifierTemplater),{pre:function(scope,element,attrs){var toolbar=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,toolbar),scope.$on("$destroy",function(){toolbar._events=void 0,$onsen.removeModifierMethods(toolbar),element.data("ons-toolbar",void 0),element=null}),$onsen.addModifierMethods(toolbar,"navigation-bar--*",element),angular.forEach(["left","center","right"],function(position){var el=element[0].querySelector(".navigation-bar__"+position);el&&$onsen.addModifierMethods(toolbar,"navigation-bar--*__"+position,angular.element(el))});var pageView=element.inheritedData("ons-page");pageView&&!inline&&pageView.registerToolbar(element),element.data("ons-toolbar",toolbar)},post:function(scope,element,attrs){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsToolbarButton",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",transclude:!0,scope:{},templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/toolbar_button.tpl",link:{pre:function(scope,element,attrs){var toolbarButton=new GenericView(scope,element,attrs),innerElement=element[0].querySelector(".toolbar-button");$onsen.declareVarAttribute(attrs,toolbarButton),element.data("ons-toolbar-button",toolbarButton),scope.$on("$destroy",function(){toolbarButton._events=void 0,$onsen.removeModifierMethods(toolbarButton),element.data("ons-toolbar-button",void 0),element=null});var modifierTemplater=$onsen.generateModifierTemplater(attrs);if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");attrs.$observe("disabled",function(value){value===!1||"undefined"==typeof value?innerElement.removeAttribute("disabled"):innerElement.setAttribute("disabled","disabled")}),scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),$onsen.addModifierMethods(toolbarButton,"toolbar-button--*",element.children()),element.children("span").addClass(modifierTemplater("toolbar-button--*")),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,attrs:attrs,element:element}),scope=element=attrs=null})},post:function(scope,element,attrs){$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen"),ComponentCleaner={decomposeNode:function(element){for(var children=element.remove().children(),i=0;i<children.length;i++)ComponentCleaner.decomposeNode(angular.element(children[i]))},destroyAttributes:function(attrs){attrs.$$element=null,attrs.$$observers=null},destroyElement:function(element){element.remove()},destroyScope:function(scope){scope.$$listeners={},scope.$$watchers=null,scope=null},onDestroy:function(scope,fn){var clear=scope.$on("$destroy",function(){clear(),fn.apply(null,arguments)})}};module.factory("ComponentCleaner",function(){return ComponentCleaner}),function(){var ngEventDirectives={};"click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" ").forEach(function(name){function directiveNormalize(name){return name.replace(/-([a-z])/g,function(matches){return matches[1].toUpperCase()})}var directiveName=directiveNormalize("ng-"+name);ngEventDirectives[directiveName]=["$parse",function($parse){return{compile:function($element,attr){var fn=$parse(attr[directiveName]);return function(scope,element,attr){var listener=function(event){scope.$apply(function(){fn(scope,{$event:event})})};element.on(name,listener),ComponentCleaner.onDestroy(scope,function(){element.off(name,listener),element=null,ComponentCleaner.destroyScope(scope),scope=null,ComponentCleaner.destroyAttributes(attr),attr=null})}}}}]}),module.config(["$provide",function($provide){var shift=function($delegate){return $delegate.shift(),$delegate};Object.keys(ngEventDirectives).forEach(function(directiveName){$provide.decorator(directiveName+"Directive",["$delegate",shift])})}]),Object.keys(ngEventDirectives).forEach(function(directiveName){module.directive(directiveName,ngEventDirectives[directiveName])})}()}(),function(){"use strict";var util={init:function(){this.ready=!1},addBackButtonListener:function(fn){this._ready?window.document.addEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.addEventListener("backbutton",fn,!1)})},removeBackButtonListener:function(fn){this._ready?window.document.removeEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.removeEventListener("backbutton",fn,!1)})}};util.init(),angular.module("onsen").service("DeviceBackButtonHandler",function(){this._init=function(){window.ons.isWebView()?window.document.addEventListener("deviceready",function(){util._ready=!0},!1):util._ready=!0,this._bindedCallback=this._callback.bind(this),this.enable()},this._isEnabled=!1,this.enable=function(){this._isEnabled||(util.addBackButtonListener(this._bindedCallback),this._isEnabled=!0)},this.disable=function(){this._isEnabled&&(util.removeBackButtonListener(this._bindedCallback),this._isEnabled=!1)},this.fireDeviceBackButtonEvent=function(){var event=document.createEvent("Event");event.initEvent("backbutton",!0,!0),document.dispatchEvent(event)},this._callback=function(){this._dispatchDeviceBackButtonEvent()},this.create=function(element,callback){if(!(element instanceof angular.element().constructor))throw new Error("element must be an instance of jqLite");if(!(callback instanceof Function))throw new Error("callback must be an instance of Function");var handler={_callback:callback,_element:element,disable:function(){this._element.data("device-backbutton-handler",null)},setListener:function(callback){this._callback=callback},enable:function(){this._element.data("device-backbutton-handler",this)},isEnabled:function(){return this._element.data("device-backbutton-handler")===this},destroy:function(){this._element.data("device-backbutton-handler",null),this._callback=this._element=null}};return handler.enable(),handler},this._dispatchDeviceBackButtonEvent=function(event){function createEvent(element){return{_element:element,callParentHandler:function(){for(var parent=this._element.parent();parent[0];){if(handler=parent.data("device-backbutton-handler"))return handler._callback(createEvent(parent));parent=parent.parent()}}}}var tree=this._captureTree(),element=this._findHandlerLeafElement(tree),handler=element.data("device-backbutton-handler");handler._callback(createEvent(element))},this._dumpParents=function(element){for(;element[0];)console.log(element[0].nodeName.toLowerCase()+"."+element.attr("class")),element=element.parent()},this._captureTree=function(){function createTree(element){return{element:element,children:Array.prototype.concat.apply([],Array.prototype.map.call(element.children(),function(child){if(child=angular.element(child),"none"===child[0].style.display)return[];if(0===child.children().length&&!child.data("device-backbutton-handler"))return[];var result=createTree(child);return 0!==result.children.length||child.data("device-backbutton-handler")?[result]:[]}))}}return createTree(angular.element(document.body))},this._dumpTree=function(node){function _dump(node,level){var pad=new Array(level+1).join(" ");console.log(pad+node.element[0].nodeName.toLowerCase()),node.children.forEach(function(node){_dump(node,level+1)})}_dump(node,0)},this._findHandlerLeafElement=function(tree){function find(node){return 0===node.children.length?node.element:1===node.children.length?find(node.children[0]):node.children.map(function(childNode){return childNode.element}).reduce(function(left,right){if(null===left)return right;var leftZ=parseInt(window.getComputedStyle(left[0],"").zIndex,10),rightZ=parseInt(window.getComputedStyle(right[0],"").zIndex,10);if(!isNaN(leftZ)&&!isNaN(rightZ))return leftZ>rightZ?left:right;throw new Error("Capturing backbutton-handler is failure.")},null)}return find(tree)},this._init()})}(),function(){"use strict";var module=angular.module("onsen");module.factory("$onsen",["$rootScope","$window","$cacheFactory","$document","$templateCache","$http","$q","$onsGlobal","ComponentCleaner","DeviceBackButtonHandler",function($rootScope,$window,$cacheFactory,$document,$templateCache,$http,$q,$onsGlobal,ComponentCleaner,DeviceBackButtonHandler){function createOnsenService(){return{DIRECTIVE_TEMPLATE_URL:"templates",cleaner:ComponentCleaner,DeviceBackButtonHandler:DeviceBackButtonHandler,_defaultDeviceBackButtonHandler:DeviceBackButtonHandler.create(angular.element(document.body),function(){navigator.app.exitApp()}),getDefaultDeviceBackButtonHandler:function(){return this._defaultDeviceBackButtonHandler},isEnabledAutoStatusBarFill:function(){return!!$onsGlobal._config.autoStatusBarFill},shouldFillStatusBar:function(element){if(this.isEnabledAutoStatusBarFill()&&this.isWebView()&&this.isIOS7Above()){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");for(var debug="ONS-TABBAR"===element.tagName?console.log.bind(console):angular.noop;;){if(element.hasAttribute("no-status-bar-fill"))return!1;if(element=element.parentNode,debug(element),!element||!element.hasAttribute)return!0}}return!1},clearComponent:function(params){params.scope&&ComponentCleaner.destroyScope(params.scope),params.attrs&&ComponentCleaner.destroyAttributes(params.attrs),params.element&&ComponentCleaner.destroyElement(params.element),params.elements&&params.elements.forEach(function(element){ComponentCleaner.destroyElement(element)})},upTo:function(el,tagName){tagName=tagName.toLowerCase();do{if(!el)return null;if(el=el.parentNode,el.tagName.toLowerCase()==tagName)return el}while(el.parentNode);return null},waitForVariables:function(dependencies,callback){unlockerDict.addCallback(dependencies,callback)},findElementeObject:function(element,name){return element.inheritedData(name)},getPageHTMLAsync:function(page){var cache=$templateCache.get(page);if(cache){var deferred=$q.defer(),html="string"==typeof cache?cache:cache[1];return deferred.resolve(this.normalizePageHTML(html)),deferred.promise}return $http({url:page,method:"GET"}).then(function(response){var html=response.data;return this.normalizePageHTML(html)}.bind(this))},normalizePageHTML:function(html){return html=(""+html).trim(),html.match(/^<(ons-page|ons-navigator|ons-tabbar|ons-sliding-menu|ons-split-view)/)||(html="<ons-page>"+html+"</ons-page>"),html},generateModifierTemplater:function(attrs,modifiers){var attrModifiers=attrs&&"string"==typeof attrs.modifier?attrs.modifier.trim().split(/ +/):[];return modifiers=angular.isArray(modifiers)?attrModifiers.concat(modifiers):attrModifiers,function(template){return modifiers.map(function(modifier){return template.replace("*",modifier)}).join(" ")}},addModifierMethods:function(view,template,element){var _tr=function(modifier){return template.replace("*",modifier)},fns={hasModifier:function(modifier){return element.hasClass(_tr(modifier))},removeModifier:function(modifier){element.removeClass(_tr(modifier))},addModifier:function(modifier){element.addClass(_tr(modifier))},setModifier:function(modifier){for(var classes=element.attr("class").split(/\s+/),patt=template.replace("*","."),i=0;i<classes.length;i++){var cls=classes[i];cls.match(patt)&&element.removeClass(cls)}element.addClass(_tr(modifier))},toggleModifier:function(modifier){var cls=_tr(modifier);element.hasClass(cls)?element.removeClass(cls):element.addClass(cls)}},append=function(oldFn,newFn){return"undefined"!=typeof oldFn?function(){return oldFn.apply(null,arguments)||newFn.apply(null,arguments)}:newFn};view.hasModifier=append(view.hasModifier,fns.hasModifier),view.removeModifier=append(view.removeModifier,fns.removeModifier),view.addModifier=append(view.addModifier,fns.addModifier),view.setModifier=append(view.setModifier,fns.setModifier),view.toggleModifier=append(view.toggleModifier,fns.toggleModifier)},removeModifierMethods:function(view){view.hasModifier=view.removeModifier=view.addModifier=view.setModifier=view.toggleModifier=void 0},declareVarAttribute:function(attrs,object){if("string"==typeof attrs["var"]){var varName=attrs["var"];this._defineVar(varName,object),unlockerDict.unlockVarName(varName)}},_registerEventHandler:function(component,eventName){var capitalizedEventName=eventName.charAt(0).toUpperCase()+eventName.slice(1);component.on(eventName,function(event){$onsen.fireComponentEvent(component._element[0],eventName,event);var handler=component._attrs["ons"+capitalizedEventName];handler&&(component._scope.$eval(handler,{$event:event}),component._scope.$evalAsync())})},registerEventHandlers:function(component,eventNames){eventNames=eventNames.trim().split(/\s+/);for(var i=0,l=eventNames.length;l>i;i++){var eventName=eventNames[i];this._registerEventHandler(component,eventName)}},isAndroid:function(){return!!window.navigator.userAgent.match(/android/i)},isIOS:function(){return!!window.navigator.userAgent.match(/(ipad|iphone|ipod touch)/i)},isWebView:function(){return window.ons.isWebView()},isIOS7Above:function(){var ua=window.navigator.userAgent,match=ua.match(/(iPad|iPhone|iPod touch);.*CPU.*OS (\d+)_(\d+)/i),result=match?parseFloat(match[2]+"."+match[3])>=7:!1;return function(){return result}}(),fireComponentEvent:function(dom,eventName,data){data=data||{};var event=document.createEvent("HTMLEvents");for(var key in data)data.hasOwnProperty(key)&&(event[key]=data[key]);event.component=dom?angular.element(dom).data(dom.nodeName.toLowerCase())||null:null,event.initEvent(dom.nodeName.toLowerCase()+":"+eventName,!0,!0),dom.dispatchEvent(event)},_defineVar:function(name,object){function set(container,names,object){for(var name,i=0;i<names.length-1;i++)name=names[i],(void 0===container[name]||null===container[name])&&(container[name]={}),container=container[name];if(container[names[names.length-1]]=object,container[names[names.length-1]]!==object)throw new Error('Cannot set var="'+object._attrs["var"]+'" because it will overwrite a read-only variable.')}var names=name.split(/\./);ons.componentBase&&set(ons.componentBase,names,object),set($rootScope,names,object)}}}function createUnlockerDict(){return{_unlockersDict:{},_unlockedVarDict:{},_addVarLock:function(name,unlocker){if(!(unlocker instanceof Function))throw new Error("unlocker argument must be an instance of Function.");this._unlockersDict[name]?this._unlockersDict[name].push(unlocker):this._unlockersDict[name]=[unlocker]},unlockVarName:function(varName){var unlockers=this._unlockersDict[varName];unlockers&&unlockers.forEach(function(unlock){unlock()}),this._unlockedVarDict[varName]=!0},addCallback:function(dependencies,callback){if(!(callback instanceof Function))throw new Error("callback argument must be an instance of Function.");var doorLock=new DoorLock,self=this;dependencies.forEach(function(varName){if(!self._unlockedVarDict[varName]){var unlock=doorLock.lock();self._addVarLock(varName,unlock)}}),doorLock.isLocked()?doorLock.waitUnlock(callback):callback()}}}var unlockerDict=createUnlockerDict(),$onsen=createOnsenService();return $onsen}])}(),window.animit=function(){"use strict";var Animit=function(element){if(!(this instanceof Animit))return new Animit(element);if(element instanceof HTMLElement)this.elements=[element];else{if("[object Array]"!==Object.prototype.toString.call(element))throw new Error("First argument must be an array or an instance of HTMLElement.");this.elements=element}this.transitionQueue=[],this.lastStyleAttributeDict=[];var self=this;this.elements.forEach(function(element,index){element.hasAttribute("data-animit-orig-style")?self.lastStyleAttributeDict[index]=element.getAttribute("data-animit-orig-style"):(self.lastStyleAttributeDict[index]=element.getAttribute("style"),element.setAttribute("data-animit-orig-style",self.lastStyleAttributeDict[index]||""))})};Animit.prototype={transitionQueue:void 0,element:void 0,play:function(callback){return"function"==typeof callback&&this.transitionQueue.push(function(done){callback(),done()}),this.startAnimation(),this},queue:function(transition,options){var queue=this.transitionQueue;if(transition&&options&&(options.css=transition,transition=new Animit.Transition(options)),transition instanceof Function||transition instanceof Animit.Transition||(transition=transition.css?new Animit.Transition(transition):new Animit.Transition({css:transition})),transition instanceof Function)queue.push(transition);else{if(!(transition instanceof Animit.Transition))throw new Error("Invalid arguments");queue.push(transition.build())}return this},wait:function(seconds){return this.transitionQueue.push(function(done){setTimeout(done,1e3*seconds)}),this},resetStyle:function(options){function reset(){self.elements.forEach(function(element,index){element.style[Animit.prefix+"Transition"]="none",element.style.transition="none",self.lastStyleAttributeDict[index]?element.setAttribute("style",self.lastStyleAttributeDict[index]):(element.setAttribute("style",""),element.removeAttribute("style"))})}options=options||{};var self=this;if(options.transition&&!options.duration)throw new Error('"options.duration" is required when "options.transition" is enabled.');if(options.transition||options.duration&&options.duration>0){var transitionValue=options.transition||"all "+options.duration+"s "+(options.timing||"linear"),transitionStyle="transition: "+transitionValue+"; -"+Animit.prefix+"-transition: "+transitionValue+";";this.transitionQueue.push(function(done){ var elements=this.elements;elements.forEach(function(element,index){element.style[Animit.prefix+"Transition"]=transitionValue,element.style.transition=transitionValue;var styleValue=(self.lastStyleAttributeDict[index]?self.lastStyleAttributeDict[index]+"; ":"")+transitionStyle;element.setAttribute("style",styleValue)});var removeListeners=util.addOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),reset(),done()}),timeoutId=setTimeout(function(){removeListeners(),reset(),done()},1e3*options.duration*1.4)})}else this.transitionQueue.push(function(done){reset(),done()});return this},startAnimation:function(){return this._dequeueTransition(),this},_dequeueTransition:function(){var transition=this.transitionQueue.shift();if(this._currentTransition)throw new Error("Current transition exists.");this._currentTransition=transition;var self=this,called=!1,done=function(){if(called)throw new Error("Invalid state: This callback is called twice.");called=!0,self._currentTransition=void 0,self._dequeueTransition()};transition&&transition.call(this,done)}},Animit.cssPropertyDict=function(){var styles=window.getComputedStyle(document.documentElement,""),dict={},a="A".charCodeAt(0),z="z".charCodeAt(0);for(var key in styles)if(styles.hasOwnProperty(key)){key.charCodeAt(0);a<=key.charCodeAt(0)&&z>=key.charCodeAt(0)&&"cssText"!==key&&"parentText"!==key&&"length"!==key&&(dict[key]=!0)}return dict}(),Animit.hasCssProperty=function(name){return!!Animit.cssPropertyDict[name]},Animit.prefix=function(){var styles=window.getComputedStyle(document.documentElement,""),pre=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1];return pre}(),Animit.runAll=function(){for(var i=0;i<arguments.length;i++)arguments[i].play()},Animit.Transition=function(options){this.options=options||{},this.options.duration=this.options.duration||0,this.options.timing=this.options.timing||"linear",this.options.css=this.options.css||{},this.options.property=this.options.property||"all"},Animit.Transition.prototype={build:function(){function createActualCssProps(css){var result={};return Object.keys(css).forEach(function(name){var value=css[name];name=util.normalizeStyleName(name);var prefixed=Animit.prefix+util.capitalize(name);Animit.cssPropertyDict[name]?result[name]=value:Animit.cssPropertyDict[prefixed]?result[prefixed]=value:(result[prefixed]=value,result[name]=value)}),result}if(0===Object.keys(this.options.css).length)throw new Error("options.css is required.");var css=createActualCssProps(this.options.css);if(this.options.duration>0){var transitionValue=util.buildTransitionValue(this.options),self=this;return function(callback){var elements=this.elements,timeout=1e3*self.options.duration*1.4,removeListeners=util.addOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),callback()}),timeoutId=setTimeout(function(){removeListeners(),callback()},timeout);elements.forEach(function(element,index){element.style[Animit.prefix+"Transition"]=transitionValue,element.style.transition=transitionValue,Object.keys(css).forEach(function(name){element.style[name]=css[name]})})}}return this.options.duration<=0?function(callback){var elements=this.elements;elements.forEach(function(element,index){element.style[Animit.prefix+"Transition"]="none",element.transition="none",Object.keys(css).forEach(function(name){element.style[name]=css[name]})}),elements.length&&elements[0].offsetHeight,window.requestAnimationFrame?requestAnimationFrame(callback):setTimeout(callback,1e3/30)}:void 0}};var util={normalizeStyleName:function(name){return name=name.replace(/-[a-zA-Z]/g,function(all){return all.slice(1).toUpperCase()}),name.charAt(0).toLowerCase()+name.slice(1)},capitalize:function(str){return str.charAt(0).toUpperCase()+str.slice(1)},buildTransitionValue:function(params){params.property=params.property||"all",params.duration=params.duration||.4,params.timing=params.timing||"linear";var props=params.property.split(/ +/);return props.map(function(prop){return prop+" "+params.duration+"s "+params.timing}).join(", ")},addOnTransitionEnd:function(element,callback){if(!element)return function(){};var fn=function(event){element==event.target&&(event.stopPropagation(),removeListeners(),callback())},removeListeners=function(){util._transitionEndEvents.forEach(function(eventName){element.removeEventListener(eventName,fn)})};return util._transitionEndEvents.forEach(function(eventName){element.addEventListener(eventName,fn,!1)}),removeListeners},_transitionEndEvents:function(){return"webkit"===Animit.prefix||"o"===Animit.prefix||"moz"===Animit.prefix||"ms"===Animit.prefix?[Animit.prefix+"TransitionEnd","transitionend"]:["transitionend"]}()};return Animit}(),window.ons.notification=function(){var createAlertDialog=function(title,message,buttonLabels,primaryButtonIndex,modifier,animation,callback,messageIsHTML,cancelable,promptDialog,autofocus,placeholder){var inputEl,dialogEl=angular.element("<ons-alert-dialog>"),titleEl=angular.element("<div>").addClass("alert-dialog-title").text(title),messageEl=angular.element("<div>").addClass("alert-dialog-content"),footerEl=angular.element("<div>").addClass("alert-dialog-footer");modifier&&dialogEl.attr("modifier",modifier),dialogEl.attr("animation",animation),messageIsHTML?messageEl.html(message):messageEl.text(message),dialogEl.append(titleEl).append(messageEl),promptDialog&&(inputEl=angular.element("<input>").addClass("text-input").attr("placeholder",placeholder).css({width:"100%",marginTop:"10px"}),messageEl.append(inputEl)),dialogEl.append(footerEl),angular.element(document.body).append(dialogEl),ons.$compile(dialogEl)(dialogEl.injector().get("$rootScope"));var alertDialog=dialogEl.data("ons-alert-dialog");buttonLabels.length<=2&&footerEl.addClass("alert-dialog-footer--one");for(var createButton=function(i){var buttonEl=angular.element("<button>").addClass("alert-dialog-button").text(buttonLabels[i]);i==primaryButtonIndex&&buttonEl.addClass("alert-dialog-button--primal"),buttonLabels.length<=2&&buttonEl.addClass("alert-dialog-button--one"),buttonEl.on("click",function(){buttonEl.off("click"),alertDialog.hide({callback:function(){callback(promptDialog?inputEl.val():i),alertDialog.destroy(),alertDialog=inputEl=buttonEl=null}})}),footerEl.append(buttonEl)},i=0;i<buttonLabels.length;i++)createButton(i);cancelable&&(alertDialog.setCancelable(cancelable),alertDialog.on("cancel",function(){callback(promptDialog?null:-1),setTimeout(function(){alertDialog.destroy(),alertDialog=null,inputEl=null})})),alertDialog.show({callback:function(){promptDialog&&autofocus&&inputEl[0].focus()}}),dialogEl=titleEl=messageEl=footerEl=null};return{alert:function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",callback:function(){}};if(options=angular.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Alert dialog must contain a message.");createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,!1,!1,!1)},confirm:function(options){var defaults={buttonLabels:["Cancel","OK"],primaryButtonIndex:1,animation:"default",title:"Confirm",callback:function(){},cancelable:!1};if(options=angular.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Confirm dialog must contain a message.");createAlertDialog(options.title,options.message||options.messageHTML,options.buttonLabels,options.primaryButtonIndex,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!1,!1)},prompt:function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",placeholder:"",callback:function(){},cancelable:!1,autofocus:!0};if(options=angular.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Prompt dialog must contain a message.");createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!0,options.autofocus,options.placeholder)}}}(),window.ons.orientation=function(){function create(){var obj={_isPortrait:!1,isPortrait:function(){return this._isPortrait()},isLandscape:function(){return!this.isPortrait()},_init:function(){return document.addEventListener("DOMContentLoaded",this._onDOMContentLoaded.bind(this),!1),"orientation"in window?window.addEventListener("orientationchange",this._onOrientationChange.bind(this),!1):window.addEventListener("resize",this._onResize.bind(this),!1),this._isPortrait=function(){return window.innerHeight>window.innerWidth},this},_onDOMContentLoaded:function(){this._installIsPortraitImplementation(),this.emit("change",{isPortrait:this.isPortrait()})},_installIsPortraitImplementation:function(){var isPortrait=window.innerWidth<window.innerHeight;"orientation"in window?window.orientation%180===0?this._isPortrait=function(){return 0===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:this._isPortrait=function(){return 90===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:this._isPortrait=function(){return window.innerHeight>window.innerWidth}},_onOrientationChange:function(){var isPortrait=this._isPortrait(),nIter=0,interval=setInterval(function(){nIter++;var w=window.innerWidth,h=window.innerHeight;isPortrait&&h>=w||!isPortrait&&w>=h?(this.emit("change",{isPortrait:isPortrait}),clearInterval(interval)):50===nIter&&(this.emit("change",{isPortrait:isPortrait}),clearInterval(interval))}.bind(this),20)},_onResize:function(){this.emit("change",{isPortrait:this.isPortrait()})}};return MicroEvent.mixin(obj),obj}return create()._init()}(),function(){"use strict";window.ons.platform={isWebView:function(){return ons.isWebView()},isIOS:function(){return/iPhone|iPad|iPod/i.test(navigator.userAgent)},isAndroid:function(){return/Android/i.test(navigator.userAgent)},isIPhone:function(){return/iPhone/i.test(navigator.userAgent)},isIPad:function(){return/iPad/i.test(navigator.userAgent)},isBlackBerry:function(){return/BlackBerry|RIM Tablet OS|BB10/i.test(navigator.userAgent)},isOpera:function(){return!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isFirefox:function(){return"undefined"!=typeof InstallTrigger},isSafari:function(){return Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0},isChrome:function(){return!!window.chrome&&!(window.opera||navigator.userAgent.indexOf(" OPR/")>=0)},isIE:function(){return!!document.documentMode},isIOS7above:function(){if(/iPhone|iPad|iPod/i.test(navigator.userAgent)){var ver=(navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/)||[""])[0].replace(/_/g,".");return parseInt(ver.split(".")[0])>=7}return!1}}}(),function(){"use strict";window.addEventListener("load",function(){FastClick.attach(document.body)},!1),(new Viewport).setup(),Modernizr.testStyles("#modernizr { -webkit-overflow-scrolling:touch }",function(elem,rule){Modernizr.addTest("overflowtouch",window.getComputedStyle&&"touch"==window.getComputedStyle(elem).getPropertyValue("-webkit-overflow-scrolling"))}),window.jQuery&&angular.element===window.jQuery&&console.warn("Onsen UI require jqLite. Load jQuery after loading AngularJS to fix this error. jQuery may break Onsen UI behavior.")}(),function(){"use strict";angular.module("onsen").run(["$templateCache",function($templateCache){for(var templates=window.document.querySelectorAll('script[type="text/ons-template"]'),i=0;i<templates.length;i++){var template=angular.element(templates[i]),id=template.attr("id");"string"==typeof id&&$templateCache.put(id,template.text())}}])}();
app/components/RDialog.js
qinfuji/vpt
import React from 'react'; import styles from '../styles/dialog.less'; import {Motion, spring} from 'react-motion'; import classnames from 'classnames'; import {$view} from './utils'; const ZINDEX = 1100; export default class RDialog extends React.Component { close(){ let {close} = this.props; close(); } open(){ let {open} = this.props; open(); } renderContent(id , context){ return $view(id , context); } renderDialog(){ let {dialogs,increase} = this.props; let _self = this; return dialogs.map(function(dialog , index){ let {title , height=300 , width=696 , opacity=1 , context} = dialog['options']; let defaultStyle = {height:0,width:0,opacity:0}; let style = {height:spring(height),width:spring(width),opacity:spring(opacity)}; let WrapedContent = _self.renderContent(dialog.id , context); return ( <Motion defaultStyle={defaultStyle} style={style} key={index}> {(value)=> <div className={classnames("dialog-inner")} style={{zIndex: ZINDEX + index}}> <div className={classnames("dialog")} style={value}>{title} <button onClick={_self.open.bind(_self)}>打开</button> <button onClick={_self.close.bind(_self)}>关闭</button> <WrapedContent/> </div> </div> } </Motion> ); }); } render() { let {dialogs} = this.props; let dlen = dialogs.length; let className = classnames( 'dialog-container' , { active: dlen > 0 } ); return ( <div className={className}> <div className={classnames("dialog-overlay")} style={{zIndex:ZINDEX + dlen - 1}}></div> {this.renderDialog()} </div> ); } }
src/react.js
malte-wessel/redux
import React from 'react'; import createAll from './components/createAll'; export const { Provider, Connector, provide, connect } = createAll(React);
app/components/sign/operations/types/vote.js
soosgit/vessel
// @flow import React, { Component } from 'react'; import { Redirect } from 'react-router'; import { Accordion, Button, Card, Checkbox, Divider, Dropdown, Form, Grid, Header, Icon, Image, Input, Label, Message, Radio, Segment, Statistic, Select, TextArea } from 'semantic-ui-react' import AccountAvatar from '../../../global/AccountAvatar'; import AccountName from '../../../global/AccountName'; import PostLink from '../../../global/PostLink'; export default class OperationsPromptVote extends Component { render() { const { opData, prompts } = this.props const avatar_author = <AccountAvatar name={opData.author} /> const avatar_voter = <AccountAvatar name={opData.voter} /> return ( <Segment attached padded> <Grid> <Grid.Row columns={3} textAlign='center' verticalAlign='top'> <Grid.Column> {avatar_voter} <Header style={{margin: 0}}> {(opData.voter) ? <AccountName name={opData.voter} /> : '<sender>'} </Header> </Grid.Column> <Grid.Column> <Header icon color='green' > <Icon name='thumbs up' size='huge' style={{margin: '0.25em 0'}} /> {(opData.weight/100).toFixed(2)}% </Header> </Grid.Column> <Grid.Column> {avatar_author} <Header style={{margin: 0}}> <AccountName name={opData.author} /> </Header> </Grid.Column> </Grid.Row> </Grid> <Segment> <Header> Voting on: <Header.Subheader> <PostLink author={opData.author} permlink={opData.permlink} /> </Header.Subheader> </Header> </Segment> </Segment> ) } }
src/HstWbInstaller.Imager.GuiApp/ClientApp/src/pages/Optimize.js
henrikstengaard/hstwb-installer
import React from 'react' import Box from "@mui/material/Box"; import Title from "../components/Title"; import {get, isNil, set} from "lodash"; import Grid from "@mui/material/Grid"; import TextField from "../components/TextField"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import BrowseOpenDialog from "../components/BrowseOpenDialog"; import Stack from "@mui/material/Stack"; import RedirectButton from "../components/RedirectButton"; import Button from "../components/Button"; import ConfirmDialog from "../components/ConfirmDialog"; const initialState = { confirmOpen: false, path: null } export default function Optimize() { const [state, setState] = React.useState({ ...initialState }) const { confirmOpen, path } = state const handleOptimize = async () => { const response = await fetch('api/optimize', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ title: `Optimizing image file '${path}'`, path }) }); if (!response.ok) { console.error('Failed to optimize image') } } const handleChange = ({name, value}) => { set(state, name, value) setState({...state}) } const handleCancel = () => { setState({ ...initialState }) } const handleConfirm = async (confirmed) => { setState({ ...state, confirmOpen: false }) if (!confirmed) { return } await handleOptimize() } const optimizeDisabled = isNil(path) return ( <Box> <ConfirmDialog id="confirm-optimize" open={confirmOpen} title="Optimize" description={`Do you want to optimize image file '${path}'?`} onClose={async (confirmed) => await handleConfirm(confirmed)} /> <Title text="Optimize" description="Optimize image file." /> <Grid container spacing="2" direction="row" alignItems="center" sx={{mt: 2}}> <Grid item xs={12} lg={6}> <TextField id="image-path" label={ <div style={{display: 'flex', alignItems: 'center', verticalAlign: 'bottom'}}> <FontAwesomeIcon icon="file" style={{marginRight: '5px'}} /> Image file </div> } value={path || ''} endAdornment={ <BrowseOpenDialog id="browse-image-path" title="Select image file" onChange={(path) => handleChange({ name: 'path', value: path })} /> } onChange={(event) => handleChange({ name: 'path', value: get(event, 'target.value' )} )} onKeyDown={async (event) => { if (event.key !== 'Enter') { return } await handleOptimize() }} /> </Grid> </Grid> <Grid container spacing="2" direction="row" alignItems="center" sx={{mt: 2}}> <Grid item xs={12} lg={6}> <Box display="flex" justifyContent="flex-end"> <Stack direction="row" spacing={2} sx={{mt: 2}}> <RedirectButton path="/" icon="ban" onClick={async () => handleCancel()} > Cancel </RedirectButton> <Button disabled={optimizeDisabled} icon="magic" onClick={async () => handleChange({ name: 'confirmOpen', value: true })} > Optimize image </Button> </Stack> </Box> </Grid> </Grid> </Box> ) }